not getting response response = httpclient.execute(request); - android

public class HTTPPoster {
public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding((Header) new BasicHeader(HTTP.DEFAULT_CONTENT_CHARSET, "application/json"));
entity = s;
request.setEntity(entity);
HttpResponse response;
response = httpclient.execute(request);
return response;
}
}
This is the code but on response = http.client.execute(request) doesn't get response. I couldn't find why.

You should call the method asynchronously. Then it will work with the same code.
Add these two lines of code to your project
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
and
make minimum sdk version to 9

You can check that if you are getting response from server or not by using following code :
HttpResponse response = httpClient1.execute(request);
Log.v("response code", response.getStatusLine()
.getStatusCode() + "");
If you get the value of response code as 200 then you are getting data from server and if the response code value >=300 then you have error at your server side.

First of all try to change the return type to String by doing these 2 steps
Change
public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException
to
public static String doPost(String url, JSONObject c) throws ClientProtocolException, IOException
AND
Change
HttpResponse response;
to
String response;
Now check the response string? Is it still null?

This is a permission issue.
Add this line <uses-permission android:name="android.permission.INTERNET" /> to your manifest file and rebuild.

Related

HttpEntity target host must not be null

I'm trying to do a POST from my android Virtual Machine to a web API that is running on my development host.
I can do a GET request and a "normal" JSON POST but when i try to do it as a MultiPart it's getting tricky.
After some research I found a good answer from Muhammad Babar Post multipart request with Android SDK. Which helped with the HTTP Entity.
So, the error :
java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=http://10.0.2.2:53918/api/Problems
It happens when the code gets to the:
HttpResponse response = client.execute(post);
My code:
public class MainActivity extends Activity {
private DefaultHttpClient mHttpClient;
private String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ServerCommunication(View view) {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient(params);
uploadUserPhoto();
}
public void uploadUserPhoto() {
try{
String uri = URLEncoder.encode( "http://10.0.2.2:53918/api/Problems","UTF-8");
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(uri);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addTextBody("Id", "7");
entityBuilder.addTextBody("DateReported", "22/04/2015");
entityBuilder.addTextBody("Category", "C");
HttpEntity entity = entityBuilder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity);
Log.v("result", result);
}
catch(Exception e)
{
e.printStackTrace();
}
}
Please help me resolve the IllegalStateException above.
The URLEncoder is meant to encode query parameters not to create a URI with scheme, host, and port. Instead move the URI to the constructor of the HttpPost for example new HttpPost("http://10.0.2.2").
Also, this API was deprecated at API Level 22, please see the documentation for the newer alternative API.

Socket closed exception when trying to read httpResponse

I have a method to connect to send post data to a webservice and get the response back as follow:
public HttpResponse sendXMLToURL(String url, String xml, String httpClientInstanceName) throws IOException {
HttpResponse response = null;
AndroidHttpClient httpClient = AndroidHttpClient.newInstance(httpClientInstanceName);
HttpPost post = new HttpPost(url);
StringEntity str = new StringEntity(xml);
str.setContentType("text/xml");
post.setEntity(str);
response = httpClient.execute(post);
if (post != null){
post.abort();
}
if (httpClient !=null){
httpClient.close();
}
return response;
}
Then, in my AsyncTask of my fragment, I try to read the response using getEntity():
HttpResponse response = xmlUtil.sendXMLToURL("url", dataXML, "getList");
//Check if the request was sent successfully
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// Parse result to check success
responseText = EntityUtils.toString(response.getEntity());
if (!xmlParser.checkForSuccess(responseText, getActivity())){
//If webservice response is error
///TODO: Error management
return false;
}
}
And when I reach that line:
responseText = EntityUtils.toString(response.getEntity());
I get an exception: java.net.SocketException: Socket closed.
This behavior doesn't happen all the time, maybe every other time.
Just write
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(your url);
HttpResponse response = client.execute(post);
it should work.No need to write codes which makes confusion.
I also experienced the 'socket closed' exception when using a client instance built using HttpClientBuilder. In my case, I was calling HttpRequestBase.releaseConnection() on my request object within a finally block before processing the response object (in a parent method). Flipping things around solved the issue... (working code below)
try {
HttpResponse response = httpClient.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
// Do something interesting with responseBody
} catch (IOException e) {
// Ah nuts...
} finally {
// release any connection resources used by the method
request.releaseConnection();
}

Post Parameters in Android Request

I am doing an Android application and I have a problem doing my request against my own server. I have made the server with Play Framework, and I get the parameters from a Json:
response.setContentTypeIfNotSet("application/json; charset=utf-8");
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(getBody(request.body));
Long id =jsonElement.getAsJsonObject().get("id").getAsLong();
When I make my GET request against my server, all is ok. But when I make a POST request, my server return me an unknown error, something about there is a malformed JSON or that it is unable to find the element.
private ArrayList NameValuePair> params;
private ArrayList NameValuePair> headers;
...
case POST:
HttpPost postRequest = new HttpPost(host);
// Add headers
for(NameValuePair h : headers)
{
postRequest.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty())
{
postRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(postRequest, host);
break;
I have tried to do with the params of the request, but it was a failure:
if(!params.isEmpty())
{
HttpParams HttpParams = new BasicHttpParams();
for (NameValuePair param : params)
{
HttpParams.setParameter(param.getName(), param.getValue());
}
postRequest.setParams(HttpParams); }
And there is the different errors, depends on the request I make. All of them are 'play.exceptions.JavaExecutionException':
'com.google.gson.stream.MalformedJsonException'
'This is not a JSON Object'
'Expecting object found: "id"'
I wish somebody can help me.
Here is a simple way to send a HTTP Post.
HttpPost httppost = new HttpPost("Your URL here");
httppost.setEntity(new StringEntity(paramsJson));
httppost.addHeader("content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
You would be better off using the JSON String directly instead of parsing it here. Hope it helps
Try this,It may help u
public void executeHttpPost(String string) throws Exception
{
//This method for HttpConnection
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("URL");
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("Name",string));
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
client.execute(request);
System.out.println("after sending :"+request.toString());
}
catch(Exception e) {System.out.println("Exp="+e);
}
}

how to post data using JSON for httpPost in Android

I have an example json as below:
{
"Passwd":"String content",
"Userme":"String content"
}
how to construct the JSON String as above and give it as argument to HttpPost in Android.?
Can anyone help me in sorting out this issue.
thanks in Advance,
You can make use of JSONObject to create a simple json like { "Passwd":"String content", "Userme":"String content" } try something like this.
String json="";
JSONObject jobj = new JSONObject();
jobj.put("Userme", "Username");
jobj.put("Passwd", "PasswordValue");
json = jobj.toString();
Above String can be sent as one of the parameter using HTTP POST easily. Below function takes url and json as parameters to make POST request.
private void httpPost(String json,String url) throws ClientProtocolException, IOException{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("json", json));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpClient.execute(httpPost);
}

Android: How get the status-code of an HttpClient request

I want to download a file and need to check the response status code (ie HTTP /1.1 200 OK).
This is a snipped of my code:
HttpGet httpRequest = new HttpGet(myUri);
HttpEntity httpEntity = null;
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpRequest);
...
How do i get the status-code of the response?
This will return the int value:
response.getStatusLine().getStatusCode()
if (response.getStatusLine().getStatusCode()== HttpsURLConnection.HTTP_OK){
...
}
Use code() function of response to get its HTTP code:
val code = response.code()

Categories

Resources