I'm currently trying to get some data via a 'uri' using the following code in java:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(uri);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream stream = entity.getContent();
callString = stream.toString();
return callString;
}
However this isn't working. Does anyone know what I'm doing wrong here?
You cannot print out the input stream like that... instead, do something like this:-
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://ichart.finance.yahoo.com/table.csv?s=MSFT");
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
if (entity != null) {
Scanner scanner = new Scanner(entity.getContent());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
The printout looks like this:-
1994-02-02,84.75,85.50,84.00,84.00,40924800,2.09
1994-02-01,85.00,85.75,84.50,85.12,44003200,2.12
1994-01-31,85.25,85.87,84.75,85.12,62566400,2.12
1994-01-28,84.50,85.50,84.25,84.87,41875200,2.11
1994-01-27,84.00,84.75,83.25,84.25,51129600,2.10
1994-01-26,85.00,85.00,84.00,84.25,50489600,2.10
1994-01-25,85.25,85.37,84.00,85.12,70361600,2.12
...
Its a total guess but shouldn't it be:
String uri = "ichart.finance.yahoo.com/table.csv?s=MSFT"
HttpData data = HttpRequest.get(uri);
System.out.println(data.content);
you are trying to download a file and getEntity is used get an object for a type you have specified. IMHO this wont work.
You need to code which will actually read the response stream and read contents out of it...
What are you trying to do ?
To read the resulting entity to a String use EntityUtils.toString(HttpEntity) or EntityUtils.toString(HttpEntity, String) if you know the character set.
If you are getting NetworkOnMainThreadException then that means you are calling client.execute(get); on the main thread which is an exception thrown on Honeycomb and higher. See http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html for details. The solution is to run this in a new thread.
Related
I consulted the API documentation and sent it successfully in api explorer-> Envelopes: create. I also got json & request path & token. I used httpclient post in java and received Object moved Object moved to here . Does anyone know what I missed?
`
DocsignDocument docsignDocument = new DocsignDocument();
docsignDocument.setDocumentBase64
docsignDocument.setDocumentId("1");
docsignDocument.setFileExtension("pdf");
docsignDocument.setName("Test.pdf");
list.add(docsignDocument);
Recipients recipients = new Recipients();
Signers signers = new Signers();
signers.setEmail("xxxx");
signers.setName("Qin");
signers.setRecipientId("1");
Signers signers1 = new Signers();
signers1.setEmail("xxx#qq.com");
signers1.setName("OYX");
signers1.setRecipientId("2");
List<Signers> signersList = new ArrayList<>();
signersList.add(signers);
signersList.add(signers1);
recipients.setSigners(signersList);
dataJson.put("documents",list);
dataJson.put("emailSubject","TEST");
dataJson.put("recipients",recipients);
dataJson.put("status","sent");
String data = dataJson.toJSONString();
String results2 = HttpDocusignUtils.httpPostJson("https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes",access_token,data)`
post request:
public static String httpPostJson(String uri, String token, String obj) {
String result = "";
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "application/json"); // 添加请求头
httpPost.addHeader("Authorization","Bearer "+token);
httpPost.addHeader("Accept-Encoding","gzip,deflate,sdch");
httpPost.setEntity(new StringEntity(obj));
System.out.println(httpPost);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
result = convertStreamToString(instreams);
System.out.println(result);
}
} catch (Exception e) {
e.getMessage();
}
return result;
}
https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes is not a valid DocuSign endpoint.
The Account Server (account-d.docusign.com) is used to get a token and make a UserInfo call to determine the correct base URL for a particular account.
Because you're in the Demo environment, your base url will begin with https://demo.docusign.net
Well, one issue is that the the Document model in Java is Document from
import com.docusign.esign.model.Document;
To debug, I suggest using the DocuSign API logging feature. Then update (edit) your question to include the JSON shown in the log.
Were you able to run the code examples for Java? See eg-03-java-auth-code-grant
Also, please tell us (by editing your question) what you are trying to do.
Creates envelopes - Use Base Url in Api Call
https://demo.docusign.net/restapi/v2.1/accounts/
Error Reason is use Wrong url - https://account-d.docusign.com/restapi/v2.1/accounts/
DocuSign Developers Documentation
I want to get just ID from httpResponse after I did HttpGet.
This is my code:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:80/api/");
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println(httpResponse);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
which returns this:
{"list":[{"timestamp":{"$date":"2014-08-01T08:37:54.058Z"},"nameGroup":false,"_id":{"$oid":"53db5045ccf2b2399e0e6128"},"created":{"$date":"2014-08-01T08:31:01.139Z"}],"name":"John"}]}
But I just want Oid not the whole thing. Any idea?
Thanks
Strint you've got is json encoded data, so you need to decode it and than you are able to access the field "oid". There are several libaries around to acomplish this job:
gson
JsonSimple
Jackson etc.
My favorite for small projects is gson
Using Jackson or Gson, you can parse the response JSON and get exactly the part you need.
If you don't need the whole result, then there is no point in creating a reference object, just manually traverse the json document, e.g.
mapper.readTree(responseText).get("foo").get("bar")
I think instead of using a library just to get value of one parameter is not appropriate if you have other options available. I would suggest you to parse the json on yor own using the APIs provided. You can try following:
try {
JSONObject obj = new JSONObject(your_json_string);
String value= null;
if (obj != null && obj.has(YOUR_KEY_FOR_PARAM)) {
value = obj.getString(YOUR_KEY_FOR_PARAM));
}
}
This has now come to a point where I cannot take it anymore! i have seen a lot of people have had the same problem as this one but their solution do not work for me.
I am trying to call a REST service from my Android application. I am still new to Android BTW.
The calling code looks like this:
String httpResult = "";
HttpClient httpClient = new DefaulthttpClient();
HttpContext httpContext = new BasicHttpContext();
String url = myURL;
HttpGet httpGet = new HttpGet(myURL);
HttpResponse response = httpClient.execute(httpGet, httpContext);
//receive response in input stream
InputStream is = response.getEntity().getContent();
//convert the stream into a string
if(is != null){
//call method that will convert stream to string
httpResult = cString(is);
}else{
httpResult = "Error";
}
When I debug the code, I see that throws an exception when the compiler hits the "HttpClient httpClient = new DefaultHttpClient()" line of code and shows "No Source Found" screen.
"No Source Found"occurred when you debug a class without the source file.
You should just use F6 to step over when debugging.
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
I'm trying out the twitter streaming api. I could succesfully filter tweets by using curl, as stated here:
curl -d #tracking http://stream.twitter.com/1/statuses/filter.json -u <user>:<pass>
where tracking is a plain file with the content:
track=Berlin
Now I tried to do the same thing in JavaSE, using Apache's HTTPComponents:
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(<user>, <pass>);
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
HttpPost httpPost = new HttpPost("http://stream.twitter.com/1/statuses/filter.json");
HttpParams params = new BasicHttpParams();
params = params.setParameter("track", "Berlin");
httpPost.setParams(params);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String t;
BufferedReader br = new BufferedReader(new InputStreamReader(instream));
while(true) {
t = br.readLine();
if(t != null) {
linkedQueue.offer(t);
}
}
}
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
finally{
httpClient.getConnectionManager().shutdown();
}
When I run that, I get:
No filter parameters found. Expect at least one parameter: follow track
as a single entry in my linkedQueue. Seems the api wants the parameter in a different form, but cannot find any hint in the documentation. Can somebody share some experiences with the api or see any other problem with the code? Thanks!
EDIT
Putting the filter parameter into the params was a bad idea. As it's post data, it needs to be defined as an Entity before the request is being made:
StringEntity postEntity = new StringEntity("track=Berlin", "UTF-8");
postEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(postEntity);
That's what I was doing wrong. Thanks Brian!
I suspect you need to post the data as the contents of your HTTP post. The man page for curl -d says:
(HTTP) Sends the specified data in a
POST request to the HTTP server, in
the same way that a browser does when
a user has filled in an HTML form and
presses the submit button. This will
cause curl to pass the data to the
server using the content-type
application/x-www-form-urlencoded.
so I believe you have to set that content type and put the contents of the tracking file in the body of your post.