I need to get the response uri from the HttpResponse and parse it into name-value pairs.
I need the analog for the following .NET fragment:
string authorizationRequestParameters = string.Format("client_id={0}&response_type=code&scope={1}&access_type=offline", ClientID, Scope);
Uri authorizationRequestUri = new Uri(OauthHost.AbsoluteUri + "?" + authorizationRequestParameters);
HttpWebResponse authorizationResponse = DoGet(authorizationRequestUri, cookies);
NameValueCollection authorizeResponseParameters = HttpUtility.ParseQueryString(authorizationResponse.ResponseUri.Query);
string callbackCode = authorizeResponseParameters["code"];
The necessary condition is, that in Java version DoGet method returns apache HttpResponse.
The way I tried to do this:
HttpResponse resp = hch.doGet("http://...?client_id=...&response_type=...&scope=...&access_type=...");
HttpEntity entity = resp.getEntity();
InputStream instream = entity.getContent();
System.out.print(IOUtils.toString(instream, "UTF-8"));
I can receive the html-content this way, but I need just response Uri, the part of it, that contains parameters.
How can I do that?
It seems like the HttpWebResponse.ResponseUri property comes from either a Content-Location header or it is a request URI. So something like this should work:
final String uri = "http://...?client_id=...&response_type=...&scope=...&access_type=...";
final HttpResponse resp = hch.doGet(uri);
final String contentLocation = resp.getFirstHeader ("Content-Location");
final String responseURI = contentLocation != null ? contentLocation : uri;
Related
I have a uri like
http://localhost/?name=foo&value=bar
And I use
org.apache.http.client.utils.URLEncodedUtils.parse(URI uri, String encoding)
to get a list of NameValuePairs, and it works nicely. But now I have need also the possibility to parse Chinese charecters, e.g.:
http://localhost/?name=生产者&value=单车
But URLEncodedUtilsparse fails to parse these characters correctly. How can I retrieve them and get a list of NameValuePairs again?
You can try like this:
String query1 = URLEncoder.encode("生产者", "UTF-8");
String query2 = URLEncoder.encode("单车", "UTF-8");
String url = "http://localhost/?name=" + query1 + "&value=" + query2;
Also check the java.net.URLEncoder
I faced the similar situation. URLEncodedUtils must be used with StringEntity. UrlEncodedFormEntity is broken.
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(
URL);
List<NameValuePair> param_data = new ArrayList<>();
param_data.add(new BasicNameValuePair("name", [STRING_FOREIGN CHARS));
String s = URLEncodedUtils.format(param_data, java.nio.charset.Charset.forName("UTF-8"));
StringEntity entity = new StringEntity(s, java.nio.charset.Charset.forName("UTF-8"));
postRequest.setEntity(entity); // don't use postRequest.setEntity(new UrlEncodedFormEntity(param_data));
HttpResponse response = httpClient.execute(postRequest);
..[snipped] do whatever you want with response
I use simple code to get XML content.
but I have a trouble if my server doesn't work, I get last success response.
I tried all methods:
send every time another URI
setHeader Cache-Content How to prevent Android from returning a cached response to my HTTP Request?
I tried even HttpURLConnection with GET.
but nothing helps
DefaultHttpClient client = new DefaultHttpClient();
String fullPath = path + name;
HttpGet request = new HttpGet(fullPath);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
//....decode input string
I am trying to post xml data to API using HTTP post method with credentials but a getting HTTP/1.1 400 Bad Request error .. Can anyone pl help me out ....
Here is my sample code:
BufferedReader br = new BufferedReader(new FileReader(new File("Data.xml")));
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!= null){
sb.append(line.trim());
}
System.out.println("xml: "+sb);
params=sb.toString();
HttpPost request = new HttpPost("*****************url***************");
String urlaparam=URLEncoder.encode("importFormatCode:1&data:"+params,"UTF-8");
String userCredentials = "****:******";
byte[] auth = Base64.encodeBase64(userCredentials.getBytes());
StringEntity entity=new StringEntity(urlaparam);
request.addHeader("Content-type","application/x-www-form-urlencoded");
request.addHeader("Accept", "application/xml");
request.addHeader("Accept-Language", "en-US,en;q=0.5");
request.addHeader("Authorization", "Basic " + new String(auth));
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine());
System.out.println(request);
}
catch(Exception e)
{
}
First of all, your form parameters are not encoded correctly. You are using colon (:) to separate keys from their values, but instead, the equal sign (=) must be used:
Wrong: "importFormatCode:1&data:" + params
Correct: "importFormatCode=1&data=" + params
(See also W3C.org - Forms in HTML Documents - application/x-www-form-urlencoded)
Apart from that, you must not URL-encode the entire string but only the keys and the values. Otherwise you'll also encode the separator characters = and &!
The easiest way is to use the existing utility class org.apache.http.client.utils.URLEncodedUtils (assuming that you're using Apache HTTP Components):
String xmlData = // your xml data from somewhere
List<NameValuePair> params = Arrays.asList(
new BasicNameValuePair("importFormatCode", "1"),
new BasicNameValuePair("data", xmlData)
);
String body = URLEncodedUtils.format(params, encoding); // use encoding of request
StringEntity entity = new StringEntity(body);
// rest of your code
Below is a snipped from a Java Client that connects to a website and uploads a file via the POST method. I have to reproduce this client in a Visual Studio environment, but I don't see any equivalent functions in the .NET environment for the setEntity() function used in the Java.
Everything I've found points to using this...
public void uploadFile(File uploadFile, String partner, String key,
String baseUrl,boolean isPartner) throws IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1
);
String url = baseUrl + "?" + (isPartner ? "partnerId" : "ori") + "="
+ partner.toUpperCase() + "&authKey="
+ key+ "&key="
+ key;
HttpPost httppost = new HttpPost(url);
MultipartEntity multipartEntity = new MultipartEntity();
ContentBody contentBody = new FileBody(uploadFile, "text/xml");
multipartEntity.addPart("dataFile", contentBody);
httppost.setEntity(multipartEntity);
HttpResponse response;
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
Everything I've found in Visual studio uses something like this below for the POST method. The WebRequest object has no obvious way of adding the parameters I need.
Dim request As WebRequest = WebRequest.Create("http://Test.com/import?partnerId=2&authKey=XdUa")
request.Method = "POST"
Dim postData As String = StrData
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "dataStr"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
Any guidance would be greatly appreciated. If my question is not clear, let me know, I'll try again.
You can add following code snippet to add the parameter
request.ContentType="application/x-www-form-urlencoded"
Dim postData As String = "name1="+value1+"&name2="+value2
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Rest will remain same.
I need to send post request with data in format like key=value and I am working that like ( url is url of ws and that is ok )
HttpEntityEnclosingRequestBase post=new HttpPost();
String result = "";
HttpClient httpclient = new DefaultHttpClient();
post.setURI(URI.create(url));
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
for (Entry<String, String> arg : args.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(arg.getKey(), arg
.getValue()));
}
http.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = getStringFromStream(instream);
instream.close();
}
return result;
This is ok when I send String data. My question is what to modify when one parameter is picture adn others are strings ?
When you are using multiple data types to send over a HttpClient you must use MultipartEntityBuilder(Class in org.apache.http.entity.mime)
try this out
MultipartEntityBuilder s= MultipartEntityBuilder.create();
File file = new File("sample.jpeg");
String message = "This is a multipart post";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
System.out.println(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, "sample.jpeg");
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
HttpEntity entity = builder.build();
httppost.setEntity(entity);
}
If you are looking to send the image as the data portion of the post request, you can follow some of the links posted in the comments.
If the image / binary data must absolutely be a header (which I wouldn't recommend), then you should use the encodeToString method inside of the Base64 Android class. I wouldn't recommend this for big images though since you need to load the entire image into memory as a byte array before you can even convert it to a string. Once you convert it to a string, its also 4/3 its previous size.
I think the answer you're looking for is in this post:
How to send an image through HTTPPost?
Emmanuel