I'm getting exceptions when I'm trying to POST and my JSON has some international characters.
This is code that I use:
HttpPost request = new HttpPost(serviceURL + url);
request.addHeader("Authorization", "Basic " + Preferences.getAuthorizationTicket(mContext));
request.addHeader("DeviceSerialNumber", Utility.getDeviceSerialNumber(mContext));
request.addHeader("OSVersion", "Android v" + Build.VERSION.RELEASE);
StringEntity entity = new StringEntity(requestData);
entity.setContentType("application/json;charset=UTF-8");
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setEntity(entity);
ResponseHandler<String> handler = new BasicResponseHandler();
response.Body = mHttpClient.execute(request, handler);
response.Code = HttpURLConnection.HTTP_OK;
response.Message = "OK";
And this is error I'm getting:
org.apache.http.client.HttpResponseException:
Bad Request at
org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:71)
at
org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
at
com.idatt.common.AsyncProcessor.processPOST(AsyncProcessor.java:550)
at
com.idatt.common.AsyncProcessor.PostMail(AsyncProcessor.java:367)
at
com.idatt.common.AsyncProcessor.doInBackground(AsyncProcessor.java:120)
at
com.idatt.common.AsyncProcessor.doInBackground(AsyncProcessor.java:28)
at
android.os.AsyncTask$2.call(AsyncTask.java:185)
at
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at
java.util.concurrent.FutureTask.run(FutureTask.java:137)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
at
java.lang.Thread.run(Thread.java:1096)
When requestData doesn't have any international (russian, polish, etc) letters than it works fine. What do I miss? Or better yet how do I get traffic from emulator captured in Fiddler or something?
I believe you should specify UTF-8 charset when you create StringEntity:
StringEntity entity = new StringEntity(requestData,"utf-8");
http://developer.android.com/reference/org/apache/http/entity/StringEntity.html#StringEntity(java.lang.String, java.lang.String)
Related
android get request exception "java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=http://stage1-go.university:80/user/profile{"userId":"0"}"
Hi, I tried to make the Get request, code here:
public InputStream setGetRequest(String concreteUrl, String jsonAsString) throws IOException {
String url = protocol + siteUrl + ":" + httpPort + "/" + concreteUrl + jsonAsString;
url = URLEncoder.encode(url, "UTF-8");
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("sessid", ClientAPI.getSessionId());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpClient client = new DefaultHttpClient();
String getServerString = client.execute(httpGet, responseHandler);
return null;
}
and here my logs:
12-11 17:59:50.731 2715-2733/com.podorojnik E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-312
Process: com.podorojnik, PID: 2715
java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=http://stage1-go.university:80/user/profile{"userId":"0"}
at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:653)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
at com.zeoalliance.internship.pilotproject.server.NetworkRequest.setGetRequest(NetworkRequest.java:100)
at com.zeoalliance.internship.pilotproject.server.NetworkRequest.getInputStream(NetworkRequest.java:60)
at com.zeoalliance.internship.pilotproject.server.NetworkRequest.execute(NetworkRequest.java:45)
at com.zeoalliance.internship.pilotproject.server.ClientAPI.getUserProfile(ClientAPI.java:156)
at com.zeoalliance.internship.pilotproject.activities.MainActivity$1.run(MainActivity.java:58)
at java.lang.Thread.run(Thread.java:818)
I also added a special permissions in the manifest and it didn't help me
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Can somebody help with this?
you are returning directly null value;
In your setGetRequest method put below code:
String getServerString = client.execute(httpGet, responseHandler);
return getServerString ;
instead of:
String getServerString = client.execute(httpGet, responseHandler);
return null;
Enjoy!!!
you have your path set as:
path=http://stage1-go.university:80/
stage1-go.university is not a host or even a valid URL. A top level domain like .com, .net or something like that is needed. If this would work you should be able to go to http://stage1-go.university in any browser, but that won't work - I just tried it
I am trying to send a HTTP post request to a REST service through my android app and the client runs as an async task. Here is the client:
#Override
protected Void doInBackground(Void... params) {
String address = "http://xxx.xx.x.xxx:8080/rest/manageUser/create";
StringBuilder stringBuilder = null;
ArrayList<NameValuePair> postParameters;
try {
HttpPost httpPost = new HttpPost(address);
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("userId", userId));
postParameters.add(new BasicNameValuePair("firstName", firstName));
postParameters.add(new BasicNameValuePair("lastName", lastName));
postParameters.add(new BasicNameValuePair("mobileNumber",
mobileNumber));
postParameters.add(new BasicNameValuePair("loginStatus",
loginStatus));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
// System.out.println(stringBuilder);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jobj = null;
try {
jobj = new JSONObject(stringBuilder.toString());
System.out.println(jobj.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
Also when I create the client as an standalone java class it works fine. But when I use it from my Android app as an async task as above, I get the following exception:
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:64)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response
at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:93)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
... 10 more
org.json.JSONException: End of input at character 0 of
at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
at org.json.JSONTokener.nextValue(JSONTokener.java:97)
at org.json.JSONObject.<init>(JSONObject.java:155)
at org.json.JSONObject.<init>(JSONObject.java:172)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:82)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Can anyone suggest what could be the problem. Also in my rest service, I am recieving the data with the #FormParam . Any help would be appreciated.
I think you are using wrong HTTP method. Just check HTTP Method whether it is correct or not and just try to get json that is going as part of request body.
I am getting this error, which is odd because it works from another activity calling the same async task. I can not figure out what the illegal character is in my query:
09-06 17:42:29.098 32101-32497/com.beerportfolio.beerportfoliopro E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 50: http://beerportfolio.com/app_getTopTaste.php?t=Rum
at java.net.URI.create(URI.java:727)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
at com.example.beerportfoliopro.GetTopTasteBeersJSON.readJSONFeed(GetTopTasteBeersJSON.java:139)
at com.example.beerportfoliopro.GetTopTasteBeersJSON.doInBackground(GetTopTasteBeersJSON.java:49)
at com.example.beerportfoliopro.GetTopTasteBeersJSON.doInBackground(GetTopTasteBeersJSON.java:34)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
... 5 more
Illegal character in query at index 50: http://beerportfolio.com/app_getTopTaste.php?t=Rum
It's the character at index 50, which is right after "Rum". It's probably some sort of whitespace character. You'll have to post your code for how you get/generate that URL if you want more details, but you might need to add some code to strip whitespace somewhere.
try to trim the string. It removes unwanted whitespace at the end of the string.
String url = " http://beerportfolio.com/app_getTopTaste.php?t=Rum";
HttpGet request = new HttpGet(url.trim());
Try the below
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String url = " http://beerportfolio.com/app_getTopTaste.php?t=Rum";
HttpGet request = new HttpGet(url);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
Log.i(".......",_response);
I just tried your url and i do get the response
09-06 22:05:04.547: I/.......(1460): [{"beer":"Rum Cask","rate":"5","id":"dkRDyR","breweryID":"jC0TAa"}]
As kabuko stated character 50 is after Rum. I think kabuko is right.
I guess you have space at the end of url. It is better to encode the url as below.
String query = URLEncoder.encode("Rum ", "utf-8");
String url = "http://beerportfolio.com/app_getTopTaste.php?t=" + query;
HttpGet request = new HttpGet(url);
URL encoding in Android
I was trying to connect the android application to the WCF service but it's not working. WCF is hosted on the IIS server. I don't know which one is wrong android application or WCF Service itself. WCF service is working fine when tested. Here is my WCF service code.
[ServiceContract(Namespace = "http://services.example.com")]
public interface IEmployeeInfo
{
[OperationContract]
[WebInvoke(
BodyStyle = WebMessageBodyStyle.Wrapped,
Method="Get",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "GetEmployee/?key={employeeId}" )]
Employee GetEmployee(int employeeId);
}
Here is my android code in which I am accessing the WCF service
try {
DefaultHttpClient client = new DefaultHttpClient();
// http get request
HttpGet request = new HttpGet(EMPLOYEE_SERVICE_URI + evEmployeeId.getText());
Log.d("Connect","Connecting to Server 0");
Log.d("Connect","Connecting to Server 1");
// set the hedear to get the data in JSON formate
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
//get the response
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
//if entity contect lenght 0, means no employee exist in the system with these code
if(entity.getContentLength() != 0) {
// stream reader object
Reader employeeReader = new InputStreamReader(response.getEntity().getContent());
//create a buffer to fill if from reader
char[] buffer = new char[(int) response.getEntity().getContentLength()];
//fill the buffer by the help of reader
employeeReader.read(buffer);
//close the reader streams
employeeReader.close();
Log.d("Connect","Connecting to Server 2");
//for the employee json object
JSONObject employee = new JSONObject(new String(buffer));
//set the text of text view
tvEmployeeCode.setText("Code: " + employee.getString("EmployeeId"));
tvName.setText("Name: " + employee.getString("FirstName") + " " + employee.getString("LastName"));
tvAddress.setText("Address: " + employee.getString("Address"));
tvBloodGroup.setText("Blood Group: " + employee.getString("BloodGroup"));
}
else {
text.setTextSize(R.string.text);
}
}
catch (Exception e) {
Log.d("Error",e.getMessage());
e.printStackTrace();
}
Any help is appreciated.
When I request the WCF service from android emulator applcation crashes. here the logchat.
11-17 22:56:55.566: W/dalvikvm(1174): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-17 22:56:55.616: E/AndroidRuntime(1174): FATAL EXCEPTION: main
11-17 22:56:55.616: E/AndroidRuntime(1174): java.lang.NullPointerException: println needs a message
11-17 22:56:55.616: E/AndroidRuntime(1174): at android.util.Log.println_native(Native Method)
11-17 22:56:55.616: E/AndroidRuntime(1174): at android.util.Log.d(Log.java:138)
11-17 22:56:55.616: E/AndroidRuntime(1174): at com.yyousuf.sample.EmployeeInfoActivity.onClick
There's an exception being thrown, but because you are catching all Exceptions, you don't have the details. For some reason the throwed Exception doesn't have a message set, and that's why you are getting the NullPointerException on this line
Log.d("Error",e.getMessage());
Please post more information about the real throwed exception.
I am getting the following error:
java.lang.StringIndexOutOfBoundsException: length=13243; regionStart=32; regionLength=-39
at java.lang.String.startEndAndLength(String.java:593)
at java.lang.String.substring(String.java:1474)
at com.dict.XMLParser.getResultFromXML(XMLParser.java:63)
at com.dict.InternetDictProvider.searchWord(InternetDictProvider.java:29)
at com.dict.SearchDict$SearchOnline.doInBackground(SearchDict.java:130)
at com.dict.SearchDict$SearchOnline.doInBackground(SearchDict.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:264)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
in the following code which typically gets results after parsing the XML page given as HttpResponse to a HttpGet :
retry:
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://oxforddictionaries.com/definition/"+query+"?q="+query);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String meanings=parser.getResultFromXML(StringUtils.inputStreamToString(httpEntity.getContent()));
if(meanings==null && firstRetry)
{
firstRetry=false;
query = query.substring(0, 1).toUpperCase() + query.substring(1);
break retry;
}
else if(meanings==null && !firstRetry)
return query;
result = query + ":" + meanings;
}
query = query.substring(0, 1).toUpperCase() + query.substring(1);
i think this statement create exeption so use if(null!=query&&query.length()!=0){query=...}
and if you substring your string length more than 1 in your case