I am using JSON to get response from my server.
This is code:
HttpClient httpclient = new DefaultHttpClient();
HttpClient httpclient2 = new DefaultHttpClient();
HttpResponse response;
HttpResponse response2;
try {
HttpGet request = new HttpGet(GlobalConfig.getMagazineUrl());
HttpGet request2 = new HttpGet(GlobalConfig.getMagazinePagesUrl(1));
request.addHeader("Authorization", "Basic " + Base64.encodeToString(
(GlobalConfig.getAuthString()).getBytes(),Base64.NO_WRAP));
request2.addHeader("Authorization", "Basic " + Base64.encodeToString(
(GlobalConfig.getAuthString()).getBytes(),Base64.NO_WRAP));
response = httpclient.execute(request);
StatusLine statusLine = response.getStatusLine();
response2 = httpclient2.execute(request2);
StatusLine statusLine2 = response2.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK && statusLine2.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream out2 = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
response2.getEntity().writeTo(out2);
out.close();
out2.close();
return parser(out.toString(), out2.toString());
As you can see in parser(out.toString(), out2.toString()) I return both responses as String. I would like to know how I can merge this two JSON responses in one. I don't want to merge two strings, I need merge two JSON respons in one big response. This is possible? If yes how I can do that?
Perhaps thats what you want:
...
JSONObject json = new JSONObject();
json.put("response1", new JSONObject(out.toString()));
json.put("response2", new JSONObject(out2.toString()));
Now return either json.toString() or json depending on the return type.
Related
The problem is as following :
I use httpclient to post login data to server.
While using firefox on my desktop with live headers the server redirects me to url2 witk 302, then to url3 with 302 and then I get 200 ok. In android I got the same login page and 200 OK.
Then I disabled automatic redirect handling got the response and saw 302 redirect, BUT
"String location = response.getHeaders("Location")[0].toString();" gave me the same login page url and not the one from firefox.
I have no idea why is that.
Code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uri[0]);
HttpResponse response;
String responseString = null;
HttpParams params = httpclient.getParams();
HttpClientParams.setRedirecting(params, false);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// Adding namvalue pairs here - adding correct i'm sure
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
if (statusLine.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
{
String location = response.getHeaders("Location")[0].toString();
}
response.getEntity().getContent().close();
}
Firefox headers:
What i get is : location= /login/
I'm working on a project in which I need to get some data from my app engine server which contains hebrew characters (the data is sent in json).
On server side:
resp.setHeader("Content-Type", "application/json; charset=UTF-8");
PrintWriter out = resp.getWriter();
out.print(responeData.toString());
when I'm debugging the server I see that the response data seems fine (meaning, it's showing my hebrew characters.
On the client side (android):
After executing this code, the resultData i'm getting is with ??? instead hebrew characters.
I tried all different encodings such as 'windows-1255', 'iso-8859-8'
Does anyone knows what the problem is?
Thanks!
// Create new default http client
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout Limit
HttpConnectionParams.setSoTimeout(client.getParams(), 10000);
HttpResponse response;
HttpPost post = new HttpPost(serviceURL);
try {
StringEntity se = new StringEntity(requestPayload.toString());
post.addHeader(CustomHeader.TASK_NAME.getHeaderName(), taskName);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
// Execute the request
response = client.execute(post);
// Get the response status code
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Ok
if (response != null) { // Checking response
InputStream in = response.getEntity().getContent(); // Get the data in the entity
retreturnVal = HttpCaller.readContentFromIS(in);
}
}
} catch (Exception e) {
Log.e("Error in connectivity layer, stacktrace: ", e.toString());
return null;
}
public static String readContentFromIS(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"), 8);
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
}
Assuming you are using a ServletResponse on your server, instead of calling
resp.setHeader("Content-Type", "application/json; charset=UTF-8");
you should call
resp.setContentType("application/json; charset=UTF-8");
This should have the effect of changing the encoding used in the call to getWriter() to UTF-8. I don't think that calling setHeader has the same side effect.
I had the same problem but I did
StringEntity se = new StringEntity(requestPayload.toString(), "UTF-8");
instead of
StringEntity se = new StringEntity(requestPayload.toString());
and it works fine for me, it's another solution.
I have struggled for quite some time to upload photo images from android to python appengine
This is what I have tried, in Android:
void apachePost() throws Exception {
File image = new File("/sdcard/image.jpg");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://clockinapple.appspot.com/upload");
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("type", new StringBody("photo"));
entity.addPart("data", new FileBody(image));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
Log.v(Constants.DATA, "received http response " + response);
} catch (ClientProtocolException e){
}
}
In appengine:
class UserPhoto(db.Model):
user = db.StringProperty()
blob_key = blobstore.BlobReferenceProperty()
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload = self.get_uploads()[0]
user_photo = UserPhoto(user="test", blob_key=upload.key())
db.put(user_photo)
return user_photo.key()
My logged server error is "Apache-HttpClient/UNAVAILABLE (java 1.4)"
I assume the headers are incorrect - I have tried many variations
Some of the links are have tried:
Ika Lan's snippet
tacticalnuclearstrike blog
I would really appreciate any help, I don't seem to be asking the right questions atm
This is what I have that works (Changed to a HttpGet), the Android code:
void apachePost(String url, String filename) throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse urlResponse = httpClient.execute(httpGet);
String result = EntityUtils.toString(urlResponse.getEntity());
Uri fileUri = Uri.parse(filename); // Gets the Uri of the file in the sdcard
File file = new File(new URI(fileUri.toString())); // Extracts the file from the Uri
FileBody fileBody = new FileBody(file, "multipart/form-data");
StringBody stringBody = new StringBody("Arghhh");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", fileBody);
entity.addPart("string", stringBody);
HttpPost httpPost = new HttpPost(result);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
response.getStatusLine();
Log.v(Constants.DATA, "received http response " + response);
Log.v(Constants.DATA, "received http entity " + entity);
}
The Appengine Code:
class GetBlobstoreUrl(BaseHandler):
def get(self):
upload_url = blobstore.create_upload_url('/upload/')
logging.debug(upload_url)
self.response.out.write(upload_url)
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file')
text_files = self.get_uploads('string')
blob_info = upload_files[0]
user_info = "text_files"
photo = clockin.UserPhoto(blob_key=blob_info.key(), user=user_info)
photo.put()
One thing that eludes me is what happened to the "entity.addPart("string", stringBody);"
it doesnt seem part of get_uploads in the blobstore object
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);
I'm trying to perform a POST request to a server that wants the Content-Type set to application/json with name and email as some keys. Currently, I'm getting a 406 error, which I'm assuming is working on the server side, but android can't handle the response. How can I tweak the code to get a 200 response?
HttpClient client = new DefaultHttpClient();
HttpEntity entity;
try{
JSONObject j = new JSONObject();
j.put("name" , myName);
j.put("email", myEmail);
HttpPost post = new HttpPost(targetURL);
post.setHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(j.toString(), HTTP.UTF_8);
se.setContentType("application/json");
post.setEntity(se);
HttpResponse response = client.execute(post);
entity = response.getEntity();
Log.d("response", response.getStatusLine().toString());
} catch(Exception e){Log.e("exception", e.toString());}
Does that look about right? Do I need one of those response handlers when creating the HttpClient?
This works for me with json-2.0.jar
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), MyApplication.HTTP_TIMEOUT); //Timeout Limit
HttpResponse response;
ArrayList<appResults> arrayList = new ArrayList<appResults>();
String resul;
try{
HttpGet get = new HttpGet(urls[0]);
response = client.execute(get);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
resul = convertStreamToString(in);
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<appResults>>() {}.getType();
arrayList = gson.fromJson(resul, listType);
in.close();
of course in asynctask or thread.
But 406... it seems that your format on your webserver and your app are not consistent...