I am a newbie attempting to send data from an Android app to a MySQL database set up on a localhost server via xampp. This method is supposed to put a name, username, password, phone number, and age into an arraylist of type NameValuePair.
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name", user.name));
dataToSend.add(new BasicNameValuePair("age", user.age + ""));
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
dataToSend.add(new BasicNameValuePair("phoneNumber", user.phoneNumber));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost("localhost/Register.php");
try{
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
When I run the application, I receive the following exception:
Target host must not be null, or set in parameters. scheme=null, host=null, path=localhost/Register.php
My research leads me to believe that there's a problem with the url string, but I don't know specifically what the issue is.
Thanks in advance.
(P.S. I am also aware of the awful security implications of storing a password in plain text on a database. Just trying to learn how to interact between apps and databases. Thx)
Try this code to post data if the localhost replacement doesn't work for you.
HttpParams params = new DefaultHttpParams(); // setup whatever params you what
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost("someurl");
post.setEntity(new UrlEncodedFormEntity()); // with list of key-value pairs
client.execute(post, new ResponseHandler(){}); // implement ResponseHandler to handle response correctly.
My issue was simply that I was using the wrong ip address. For some reason or another, localhost does not work. I figured out my system's ipv4 address (not 10.0.2.2) and used that and it worked.
Related
I can get to https://pushover.net/ using chrome browser, but when i try to get to the same website using java to connect to the api and send data it fails.
this is my code
HttpClient httpClient = (HttpClient) HttpClientBuilder.create()/*.setProxy(proxy)*/.build();
HttpPost post = new HttpPost("https://api.pushover.net/1/messages.json");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("token", apiToken));
nvps.add(new BasicNameValuePair("user", userKey));
nvps.add(new BasicNameValuePair("message", message));
post.setEntity(new UrlEncodedFormEntity(nvps, Charset.defaultCharset()));
//point A
HttpResponse deviceResponse = httpClient.execute(post);
//point B
it gets to point A, but then takes ages to get to point B and it gives an exception when it does.
The Exception is
org.apache.http.conn.HttpHostConnectException: Connect to api.pushover.net:443 (api.pushover.net/108.59.13.232] failed: Connection timer out: connect.
I have tried using a proxy with the below code above the rest
HttpHost proxy = new HttpHost("url",9090,"https");
httpClient = (HttpClient) HttpClientBuilder.create().setProxy(proxy).build();
This gives me a
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
I then also tried adding
Authenticator.setDefault(
new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
authUser, authPassword.toCharArray());
}
}
);
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);
but it gives the same SSLHandshakeException.
I have seen things on creating keystores, but that will only work on my machine, I want something that will work in code and allow me to deploy this app to 1000's of machines, without having to do extra manual config to each.
Is there anything Better i should be doing?
I have fixed it with this code in place of the httpClient at the beginning.
HttpHost proxy = new HttpHost(PROXY_URL, 8080);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
AuthCache authCache = new BasicAuthCache();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(PROXY_URL, 8080, AuthScope.ANY_HOST, "ntlm"), new NTCredentials(authUser, authPassword, "",PROXY_DOMAIN));
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).setRoutePlanner(routePlanner).build();
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpMethod = new HttpPost(this.transformURL(request));
BasicHttpParams params = new BasicHttpParams();
params.setParameter("name", name);
httpMethod.setParams(params);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpclient.execute(httpMethod, responseHandler);
}catch{
LOG.error("Error");
} finally {
httpclient.getConnectionManager().shutdown();
}
I have the above code, and I'm trying to pass in a name variable as a paramter to get picked up in another method by request.getParameter("name").
It doesn't seem to be working, when I debug I can see the parameters get set but when I follow it through to the next method that gets executed, it doesn't pick up the parameters.
Any suggestions?
EDIT:
I added this and it worked great
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("name", request.getParameter("name")));
httpMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Did you check this example? it uses the class BasicNameValuePair instead of BasicHttpParams as you do.
Also, the documentation for the version 3.x of HttpClient does it:
PostMethod post = new PostMethod("http://jakarata.apache.org/");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.
Update: The BasicHttpParams class is an implementation of the HttpParams interface, which as #Perception notes below, is a set of properties "that customize the behavior of the HTTP client". From the HttpParams javadoc: "HttpParams is expected to be used in 'write once - read many' mode. Once initialized, HTTP parameters are not expected to mutate in the course of HTTP message processing."
I'm trying to authenticate with Google using a simple Java program. I post to the correct URL with my credentials. I get a response with HTTP status code 200 but that doesn't contain any of the authentication tokens that I need to retrieve feeds for the user. Here's the code
private static String postData = "https://www.google.com/accounts/ClientLogin?Content-type=application/x-www-form-urlencoded&accountType=GOOGLE&Email=xxxxxxxx&Passwd=xxxxx";
public GoogleConnector(){
HttpClient client=new DefaultHttpClient();
HttpPost method=new HttpPost(postData);
try{
HttpResponse response=client.execute(method);
System.out.println(response.toString());
}
catch(Exception e){
}
Ok, the first problem you have is that 'Content-Type' needs to be a header, not a request parameter. And secondly, POST parameters should be appended to the request body, not to the request URL. Your code should look something like this:
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost("https://www.google.com/accounts/ClientLogin");
method.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(4);
postParams.add(new BasicNameValuePair("accountType", "GOOGLE"));
postParams.add(new BasicNameValuePair("Email", "xxxxxxx"));
postParams.add(new BasicNameValuePair("Passwd", "xxxxxx"));
postParams.add(new BasicNameValuePair("service", "cl"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParams);
method.setEntity(formEntity);
HttpResponse response=client.execute(method);
System.out.println(response.toString());
I have an application that uses a https post to a remote server.
Everytime I attempt to post to that server I get a response that says that I have not added the id parameter.
Here is my code
HttpHost host = new HttpHost("hostname", 443, "https");
HttpPost httppost = new HttpPost(uri);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("description", "Android"));
nameValuePairs.add(new BasicNameValuePair("type", "Android"));
nameValuePairs.add(new BasicNameValuePair("id", DeviceUtils.getID()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
String content = httppost.getEntity().toString();
HttpResponse response = httpclient.execute(host, httppost);
I have tried with and without the "custom" httphost, but I always get the same response.
Similar code has been used in a javaclient that runs on the desktop, and it works just fine.
The Id is the deviceId that has been RSA Encrypted and Base64 encoded.
Any ideas as to what I am doing wrong here.
Hi I'm having a lot of trouble submitting a simple form, I have searched around and it appears quite a few people have had the same problem but I haven't found an answer.
Here's my code so far:
public void postData(TextView txtResult, String user, String pass) throws ClientProtocolException, IOException {
HttpPost post = new HttpPost("https://www.mymeteor.ie");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", user));
nameValuePairs.add(new BasicNameValuePair("userpass", pass));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
txtResult.setText(responseText);
}
The above code will simply return the original page,
can anybody help me?
thanks
Are you sure that URL supports logging in via post that way? It looks to me like the login form sends the post data to this URL: https://www.mymeteor.ie/go/mymeteor-login-manager
I would also suspect you should be using some sort of API instead of just posting data to their login form, remotely.