can't access localhost from android emulator - java

I'm trying to call a java webservice running in my localhost, from a android application running on an emulator on the same machine, here is my code:
String url = "http://10.0.2.2:8080/MobileMiddleware/Registration";
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 30000);
HttpConnectionParams.setSoTimeout(myParams, 30000);
try {
HttpPost httppost = new HttpPost(url.toString());
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(request);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
Result = EntityUtils
.toString(response.getEntity());
Log.d(" return Result>>", Result);
}
catch (ClientProtocolException e) {}
catch (IOException e) { }
return null;
}
this code returns error message Connection timeout, the gateway could not receive a timely response from the website
help please

Related

connection time out in godaddy server

if face problem just in Godaddy server when executing google API the request return connection time out,
only this request.
but on my other servers (digital ocean and local server), it runs and everything is well and same code and the same configuration
String dataSTR = data.toString();
HttpPost request = new HttpPost("https://fcm.googleapis.com/fcm/send");
StringEntity params = new StringEntity(dataSTR, "UTF-8");
String key = "key=" + authKey;
request.addHeader("Authorization", key);
request.addHeader("content-type", "application/json");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("content-type", "charset=UTF-8");
request.setEntity(params);
System.out.println(request);
System.out.println("______");
HttpResponse response;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
System.out.println(response);
} catch (ClientProtocolException e) {
LOGGER.error(e.getMessage(), e);
return false;
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
return false;
}

Is my HTTPClient connection leaking sockets?

I have an app deployed on google app engine that uses the Apache HTTPClient. Recently as the app is getting more traffic, I have started running into exceptions where the sockets quota has been exceeded. The exception is
com.google.apphosting.api.ApiProxy$OverQuotaException: The API call remote_socket.SetSocketOptions() required more quota than is available.
I reached out to the App Engine team and they wanted me to check if my app was leaking sockets.
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.spark.com");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("param1", "val1"));
nvps.add(new BasicNameValuePair("param2", "val2"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpclient.execute(httpPost);
Document doc = null;
try {
HttpEntity entity = response.getEntity();
doc = Jsoup.parse(entity.getContent(), "UTF-8", "");
EntityUtils.consume(entity);
} finally {
response.close();
httpclient.close();
}
This is what my http connection code looks like. Am I doing something wrong which may be causing the sockets to leak? Can I do something better?
this work for me :
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
// HttpPost httppost = new HttpPost("http://rafsanjan.uni-azad.my.com/json/darkhasr.php?shdaneshjo="+value_id+"&moavenat="+value_seaction+"&darkhast="+zir_item+"&startdate=test&tozih="+ value_descration); //???
try {
URIBuilder builder = new URIBuilder();
builder.setScheme("http")
.setHost("app.my.ac.com")
.setPort(1180)
.setPath("/json2/darkhasr.php")
.addParameter("shdaneshjo", value_id)
.addParameter("moavenat", value_seaction)
.addParameter("darkhast", value_item)
.addParameter("startdatet", "0")
.addParameter("tozih", value_descration)
.build();
// .fragment("section-name");
String myUrl = builder.toString();
Log.d("url=>",myUrl);
HttpPost httppost = new HttpPost(myUrl);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(8);
//nameValuePairs.add(new BasicNameValuePair("name", name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
Log.d("RESPONSE",EntityUtils.toString(resEntity));
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}

Android No peer certificate exception

In my Android application I use http link for get JSON response from server, now they changed to https. My code is return No peer certificate exception.
What the things need to get response from server using https in Android. This is the code I used for get response from server for http.
public static DefaultHttpClient httpClient;
public static ResponseHandler<String> resHandler;
public static List<NameValuePair> nameValuePairs;
public static HttpPost httpPost;
....
httpClient = new DefaultHttpClient();
resHandler = new BasicResponseHandler();
httpPost = new HttpPost("https://www.xxx.com/.../user/renting");
nameValuePairs = new ArrayList<NameValuePair>(6);
nameValuePairs.add(new BasicNameValuePair("parking_spot_id".trim(),
spotID));
....
for (int i = 0; i < array.length; i++) {
nameValuePairs.add(new BasicNameValuePair("date[]", array[i]));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
jsonResponse = httpClient.execute(httpPost, resHandler);
Log.e("rent by day", jsonResponse);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The above code working well for using http.
1) What are the things I need to get for https.
2) What are the changes in the code.
Please help me.

Why does converting this Python POST request to Java not work?

I'm trying to convert this Python code using the Python Requests HTTP library into Java code (for Android).
import requests
payload = {"attr[val1]":123,
"attr[val2]":456,
"time":0,
"name":"Foo","surname":"Bar"}
r = requests.post("http://jakiro.herokuapp.com/api", data=payload)
r.status_code
r.text
This is what I've done so far:
protected void sendJson() {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
Log.v("SOMETHING_NAME3", "Creating POST");
HttpPost post = new HttpPost("http://jakiro.herokuapp.com/api");
json.put(MessageAttribute.SURNAME, "Bar");
json.put(MessageAttribute.VAL1, 123);
json.put(MessageAttribute.VAL2, 456);
json.put(MessageAttribute.name, "Foo");
json.put(MessageAttribute.TIME, 0);
StringEntity se = new StringEntity( json.toString() );
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
String foo = convertStreamToString(in);
Log.v("SOMETHING_NAME2", foo); // Gives me "Bad request"
}
} catch(Exception e) {
e.printStackTrace();
Log.v("SOMETHING_NAME", "Cannot Establish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
I've checked the response with response.getStatusLine().getStatusCode() and I get back a 400 from the server. The Python code works fine, but in Java on an Android device it doesn't. I can't see to figure out why though.
#Blender's link was the correct solution at the link: How to use parameters with HttpPost
The correct way to url-encode was to create BasicNameValuePairs and encode that as such:
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));

org.apache.http.client.ClientProtocolException in HttpPost

I try upload some string to server. When I try upload on server, in string:
HttpResponse response = httpclient.execute(httppost);
I have error org.apache.http.client.ClientProtocolException. All code:
public void sendString(String stringToSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpPost httppost = new HttpPost(serverAddress);
InputStreamEntity reqEntity = new InputStreamEntity( new ByteArrayInputStream(stringToSend.getBytes()), stringToSend.length());
reqEntity.setContentType("application/xml");
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) {
Log.i("SEND", "not send "+response.getStatusLine());
}else{
Log.i("SEND", "send ok "+response.getStatusLine());
}
} catch (IOException e) {
Log.w("IOException", e.toString() +" "+ e.getMessage());
}
}
This should work
public void sendString(String stringToSend) {
try {
HttpParams httpParams=new BasicHttpParams();
DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpPost httppost = new HttpPost(serverAddress);
InputStreamEntity reqEntity = new InputStreamEntity( new ByteArrayInputStream(stringToSend.getBytes()), stringToSend.length());
reqEntity.setContentType("application/xml");
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) {
Log.i("SEND", "not send "+response.getStatusLine());
}else{
Log.i("SEND", "send ok "+response.getStatusLine());
}
} catch (IOException e) {
Log.w("IOException", e.toString() +" "+ e.getMessage());
}
}

Categories

Resources