MultipartEntity not creating good request - android

I needed to send some XML to a webservices and I was able to do it with a normal StringEntity because it was just text but now I need to attach an image to it as well. I tried doing it with a MultipartEntity but I couldn't get it working with just the XML.
// Working
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost doc = new HttpPost("http://mywebservices.com");
HttpEntity entity = new StringEntity(writer.toString());
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
// not working
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost doc = new HttpPost("http://mywebservices.com");
// no difference when removing the BROWSER_COMPATIBLE
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("xml", new StringBody(writer.toString()));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
And is there a way I could see the MIME that is being send?

You simply forgot:
httppost.setEntity(entity);
By the way, it's probably good form to set the Content-Type of your parts, e.g.:
entity.addPart("xml", new StringBody(writer.toString(),"application/xml",Charset.forName("UTF-8")));
As far as seeing what's being sent, see http://hc.apache.org/httpcomponents-client-ga/logging.html (especially "wire logging") for the HttpClient logging features, and
this question for how to get it working on Android.

Another way to see what's being sent is to set up your own "server" to receive the request. You can do this on a Unix-like system with netcat. The command-line
nc -l 1234
starts a server listening on port 1234, and will echo whatever is received.
If that "server" is on a machine 10.1.2.3, you can just use a new HttpPost("http://10.1.2.3:1234") to send the message there.

I have a similar problem but I'm sending the multipart with user/pass to a acegi security system, it works with this:
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
But not with this:
try {
for (NameValuePair param : params) {
multientity.addPart(param.getName(), new StringBody(param.getValue(), Charset.forName(encoding))));
}
request.setEntity(multientity);
}

Related

Get the XML entity passed in body - HTTP Put method in Android

I wanted to retrieve the XML entity passed in body of HTTP Put method. I used the below code,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(serverSocket.accept(), new BasicHttpParams());
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
System.out.println(EntityUtils.toString(entity));
I could get the norma strings, but when trying to pass the XML entity, I could not even see the print statement.
I hope this code help you.
HttpPost httppost = new HttpPost(SERVICE_EPR);
StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse =
(BasicHttpResponse) httpclient.execute(httppost);
response.put("HTTPStatus",httpResponse.getStatusLine().toString());
PFB the solution,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
params = new BasicHttpParams();
conn.bind(socket, params);
//Extracting the information from the requested URI
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity httpEntity = ((HttpEntityEnclosingRequest)request).getEntity();
if(httpEntity != null){
InputStream instream = httpEntity.getContent();
try {
// do something useful
String myString = IOUtils.toString(instream, "UTF-8");
Log.e(TAG,">>>> http body > "+myString);
} finally {
instream.close();
}
}
Don't put any log or print statements using the data you received, I was getting 'Content already consumed' exception. I had used several logs using the httpEntity i received and that was causing the problem for me. I commented those(marked yellow) and started working.
PF the Apache doc for reference,
http://hc.apache.org/httpcomponents-core-ga/tutorial/pdf/httpcore-tutorial.pdf

Android HTTP PUT request probably differs from Post, because it doesnt work?

Here is how I use POST and it works:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
And I didnt know how to use PUT, so I got this code and I changed every "Post" to "Put"
but I dont think it works:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPut);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
When I try updating a user's account using this implementation ot PUT I get errors from the server. - "No session. Unauthorized."
When I use Chrome's postman with the same parameters, I get no problem, so I think my PUT implementation doesnt work.
You need to use the same DefaultHttpClient to make all the calls, because your session information is stored in the instance object.
If you need to use different instances, you may be able to do that getting the cookies from the login request and add them in the next requests using getCookieStore/setCookieStore.

Android and connecting to webpage with .http authentication

I need to use httpclient to connect to a webpage (Apache) running PHP scripts which is protected with .htaccess authentication.
I've been reading questions and answers (in here and other places) for an hour now, and none of the sultions is working for me. Either the methods people are using in classes like Base64.java does not exist, or the parameters are wrong.
I'm connecting to normal (non-protected webpages like this):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
nameValuePairs.add(new BasicNameValuePair("date", cDate));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
But this, naturally, doesn't help when the page is protected. So how can I, in the easiest way, pass my username and password to the connection?
You can get a Base64 here: http://iharder.sourceforge.net/current/java/base64/.
I usually do something like following for authentication:
StringBuilder authentication = new StringBuilder().append("dogT4g").append(":").append("petTheDog5");
String result = Base64.encodeBytes(authentication.toString().getBytes());
httppost.setHeader("Authorization", "Basic " + result);
Hope that solves your problem.

Sending Video using HTTP Post Multipart entity

What I want I want to send a video from my SDcard to a server. I also want to send some parameters/value with it.
I have tried I have tried the following code:
public String SendToServer(String aUrl,File aFile)
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(aUrl);
try
{
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(aFile));
entity.addPart("video[title]", new StringBody("testVideo"));
entity.addPart("video[type]", new StringBody("1"));
httpPost.setEntity(entity);
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
String Response = "";
if (response != null)
{
Response = EntityUtils.toString(resEntity);
}
return Response;
}
catch (IOException e)
{
e.printStackTrace();
}
return "Exception";
}
What is the problem When I run this code, I get stuck at this line
HttpResponse response = httpClient.execute(httpPost, localContext);
I get no exception, no response nothing at all. Can anyone please guide me, what is the problem in here?
The above code in my question was perfect, but I had the network problem. My device was connected to a hotspot(Connectify Software). When I connected to the original network, this code worked perfect.
I recommend you people to never trust a hotspot for this kind of functionality.
try using this way if want to send as content or esle I will upload the project by tonight
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(filePath), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);

application/soap+msbin1 in android

I just need to send request to webservice via normal HTTP POST inorder to get response.I passed required parameter on body well.While i run it.,i got "Cannot process the message because the content type 'text/json' was not the expected type 'application/soap+msbin1'." error.When i made research over this.,due to "Web Service required the request to have a specific Content-Type, namely "application/soap+msbin1".When i replaced expected content type.,i got Bad Request error.I donno how to recover from that.
My code:
...
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("My URL");
postMethod.setHeader( "Content-Type", "text/json");
postMethod.setHeader( "Cache-Control", "no-cache");
JSONObject json = new JSONObject();
json.put("userName", "My Username");
json.put("password", "My Password");
json.put("isPersistent",false);
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
HttpResponse response = httpClient.execute(postMethod);
...
It looks like you are trying to call WCF SOAP service. That service expects correct SOAP communication (= no JSON) and moreover it uses MS binary message encoding of SOAP messages (that is what content type describes) is not interoperable so I doubt you will be able to use it on Android device (unless you find implementation of that encoding for Java / Android).
HttpPost request = new HttpPost(url);
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setHeader("Accept", "application/json");
request.setEntity(entity);
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
}
Try using something like this. it worked for me.
Thanks.
N_JOY.

Categories

Resources