I am posting a url with params containg an underscore (_).
sample: http://sdsdsds_asasasahjhd.com/dsdsdsd/login.json?
I am posting it like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://sdsdsds_asasasahjhd.com/dsdsdsd/login.json?");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key1", "value1"));
nameValuePairs.add(new BasicNameValuePair("key2", "value2"));
nameValuePairs
.add(new BasicNameValuePair("key3", "value3"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
}
When I am inspecting httpclient.execute(httppost) I am getting IllegalArgumentException and in catch in exception details it is telling Host name cannot be null.
Please specify any solution.
I have gone through some other questions here:
java.lang.IllegalStateException: Target host must not be null, or set in parameters
Host name may not be null in HttpResponse execute for android
but no use as I am not encoding the whole url.
I have an open-source library with network implementation mechanism. It has just receiver an workaround implementation. All you need it to set the host by reflection in case of troubles:
final URI uriObj = new URI("https", host, path, null, null);
if (uriObj.getHost() == null) {
final Field hostField = URI.class.getDeclaredField("host");
hostField.setAccessible(true);
hostField.set(uriObj, host);
}
return uriObj;
The commit is here.
well it clearly states that the host name can not be null.. your url doesn't specify one..
a url is expected to be in the format
http://hostName.com/example..../example.json
HttpPost httppost = new HttpPost(String);
This contructor will attempt to form a URL instance from the provided String. If this fails, you'll be dealing with a null value.
Please post the actual URL you're using and not a sample if you want us to be able to help you further.
See this link. Apache doesnt support underscore. You should change the url
https://issues.apache.org/jira/browse/HTTPCLIENT-911
Related
I have a requirement to send some values to a service via HTTP POST. One of the parameters that gets sent must contain blanks. It is the "Key" nvp. But the service always returs a unsuccessful message, as soon as I add a value it work.
Now here is the catch, when the request is done to the same service via iphone device it works just fine when they send BLANKS, am I missing something in my request to allow blank values to be sent via NameVauePair?
Here is my NaveValuePair's
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("id","1"));
nameValuePairs.add(new BasicNameValuePair("uId",android_id));
nameValuePairs.add(new BasicNameValuePair("Key", " ")); // This value must be BLANKS
nameValuePairs.add(new BasicNameValuePair("Rate","0"));
nameValuePairs.add(new BasicNameValuePair("Notes", notes));
Here is my POST request
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(context.getResources()
.getString(R.string.url_event_rating));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response
.getEntity());
} catch (ClientProtocolException e) {
Log.d("ClientProtocolException", e.getMessage());
} catch (IOException e) {
Log.d("IOException", e.getMessage());
}
Try adding SP instead of a literal space character. This is the syntax given to you by BasicNameValuePair: http://developer.android.com/reference/org/apache/http/message/BasicNameValuePair.html (specifies a general overview of the class) and http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 (specifies the tokens accepted).
Essentially, you want to insert SP instead of " ", according to what I've read on the topic.
Edit: According to the second link above: SP = <US-ASCII SP, space (32)>. Essentially, either place a character whose value is 32 (decimal) or 0x20 (hex). Or, change your encoding in UrlEncodedFormEntity(nameValuePairs, "utf-8") to "US-ASCII".
While we send a POST request there are field in HTTP Headers to be set, like the Content-Type field with value "application/x-www-form-urlencoded", which is default type. We should whatsoever encode the value field of request body before sending it. URLEncoder.encode(String s, String charsetName) functions encode a string with given charsetName i.e, 'utf-8'. The encoding used by default is based on a very early version of the general URI percent encoding rules.
one encoding example: a string like My Name is "Marshal" will be encoded as:
My%20Name%20is%20%22Marshal%22.
So, the safest way is to set (name, value) pair after encoding with this function. That is:
value = URLEncoder.encode(value, "utf-8");
nameValuePairs.add(new BasicNameValuePair(key, value));
Ok, there might be other ways to get this to work but the following code is what worked for me.
I got it to work using the following approach.
String blanks = " ";
nameValuePairs.add(new BasicNameValuePair("Key", blanks.replaceAll(" ", "%20")));
Hope this helps someone who has encountered the same problem.
I'm using the apache http library and need to know how to add a parameter to an HTTP GET request. I've looked over How to add parameters to a HTTP GET request in Android? but the accepted answer for that adds parameters to an HTTP POST. This is my code so far but it is not working.
HttpGet get = new HttpGet("https://server.com/stuff");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("count", "5"));
HttpParams p = get.getParams();
p.setParameter("length", "5");
get.setParams(p);
String url = "https://server.com/stuff"
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("count", "5"));
HttpClient httpClient = new DefaultHttpClient();
String paramsString = URLEncodedUtils.format(nameValuePairs, "UTF-8");
HttpGet httpGet = new HttpGet(url + "?" + paramsString);
HttpResponse response = httpClient.execute(httpGet);
EDIT: Since Android SDK v22, the type NameValuePair is deprecated. I recommend using Volley, an HTTP library that makes networking for Android apps easier and most importantly, faster.
unlike POST, GET sends the parameters under the url like this:
http://myurl.com?variable1=value&variable2=value2
Where: the parameters area start from the question mark and on so the variable1 is the first param and it has "value" value...
See here for more informations.
So what you need to do is just build an url that contains also these parameters according to server needs.
EDIT:
In your case :
HttpGet get = new HttpGet("https://server.com/stuff?count=5&length=5");
...
Where: count=5 and length=5 are the parameters and the "?" mark is the beginning of the parameters definition...
I hope that helps.
I want to post to this url
http://abc.com/Registration.aspx?MailID=PickUp&UserName=as&PickUpTime=19191919&Notes=bla&DeviceId=0000
HttpPost httppost = new HttpPost("http://abc.com/Davis/Registration.aspx");
httppost.setHeader("MailID","MailID=PickUp");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("MailID","PickUp"));
nameValuePairs.add(new BasicNameValuePair("UserName","as"));
nameValuePairs.add(new BasicNameValuePair("PickUpTime",date));
nameValuePairs.add(new BasicNameValuePair("Notes",note));
nameValuePairs.add(new BasicNameValuePair("DeviceId",deviceID));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Also how can I know what url I am passing . How can I log it ?
Are you sure MailID should be in the header? From the wording of the question, it looks as if all values are in the query string (in the URL past the ? mark). But then why would you need POST for that; a GET would be sufficient.
And passing data, like MailID, in headers is almost unheard of. Querystring and POST form, those are the most popular places.
So first figure out the interface of the server page. Does it expect GET or POST (or either)? Then place the fields into the right place - either into the URL (by string concatenation), or into the entity.
Oh, and the URL you're passing is http://abc.com/Davis/Registration.aspx. Neither setHeader() nor setEntity() modifies the URL per se.
I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
My code is here
public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(result.toString());
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
what mistake i have done plz correct me because it shows me an bad request error
but when i do post in poster it shows me status as Successfull 200 ok
I do this with
httppost.setHeader("Content-type", "application/json");
Also, the new HttpPost() takes the web service URL as argument.
In the try catch loop, I did this:
HttpPost post = new HttpPost(
"https://www.placeyoururlhere.com");
post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
response = EntityUtils.toString(entity);
You can add your nameValurPairs according to how many fields you have.
Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.
If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++
If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library.
However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/
If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?
If its a REST-API Call like POST or GET to be more specific then its is very simple
Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.
Hope this helps.
I have a problem with my android app. I mean I'm using the code from one of tuts in the internet, looks like below
public static String sendLocation(String s) {
// Create a new HttpClient and Post Header
//HttpParams params = new BasicHttpParams();
//params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://google.com/read.php");
//String d = "ok";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", "mobile"));
nameValuePairs.add(new BasicNameValuePair("location", s));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// d = "CPE";
} catch (IOException e) {
// d = "E";
}
return "send";
}
}`
And the problem/bug appeared when the app try to send data to the remote server (the line below)
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
I also use the StrictMode and after that everything works, the logs shows network violation
11-08 22:34:40.020: D/StrictMode(939): StrictMode policy violation; ~duration=359 ms: android.os.StrictMode$StrictModeNetworkViolation: policy=31 violation=4
I included in the manifest file appropriate permission
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
Do you have any idea what should I do to run my app (actually send data via post to the server) without StrictMode?
The problem is that you are trying to do network calls on the main UI thread. Only use those types of methods in a separate thread.
A good example of that is here.