I try to call API with different id as shown in following code. But it only executed for first run and stop. Can Anyone help how to solve this problem?
The size of the idArray is 2.
for (int i = 0; i< idArray.size(); i++){
String id = idArray.get(i);
Thread.currentThread().sleep(3000);
String myURI1 = "https://api.bulksms.com/v1/messages/"+id;
URL url1 = new URL(myURI1);
System.out.println(myURI1);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setDoOutput(true);
request1.setRequestProperty("Authorization", "Basic " + authEncoded);
request1.setRequestMethod("GET");
request1.setRequestProperty( "Content-Type", "application/json");
BufferedReader in1 = new BufferedReader( new InputStreamReader(request1.getInputStream()));
String inputLine1;
StringBuffer response1 = new StringBuffer();
while ((inputLine1 = in1.readLine()) != null) {
response1.append(inputLine1);
}
}
I would like you to refer #hgoebl answer to Single URLConnection to fetch only the first line in java using BufferedReader.
"HttpURLConnection cannot be reused, but it can reuse an open connection to the same server internally by setting the header Connection: keep-alive. It doesn't make sense if you connect to different servers, obviously.
"
when you open a connection via URLConnection to read the content of a Webpage,
try {
URL url = new URL("https://stackoverflow.com/questions/46939965/does-java-urlconnection-send-metadata");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection;
connection = (HttpURLConnection) urlConnection;
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String current;
while((current = in.readLine()) != null) {
urlString += current;
}
}catch(IOException e) {
e.printStackTrace();
}
what will Java leave for Information?
Will statistical data like the Webbrowser saved? Will that be the "Java"?
Thx for help,
~Corn
HTTP "metadata" is normally sent in the headers. The one that would indicate the web browser is typically called "USER_AGENT." I do not believe Java will populate these headers for you implicitly.
I am working on a Server-Client application. For part of the requests, I need to generate a piece of Json String on Server side and send it to Client. The Json String was generated correctly on the server side according to the Server log. But on the Android client side, the String was changed and cannot be parsed as correct Json String.
Here are some related code.
Generate Json String on Server side:
#RequestMapping(value="/resourceList/{actType}/{type}/{id}")
#ResponseBody public Object personList(#PathVariable int actType, #PathVariable int type, #PathVariable int id){
ArrayList<ItemBase> list = new ArrayList();
......
return new ArrayList();
}
This generates following Json code:
[{"countryID":1,"locationID":5,"siteID":5,"brief":"shark point","userID":0,"status":"normal","rank":0.0,"id":2,"timestamp":1471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"displayName":"halik","pic":"3.jpg","actType":1,"type":64}]
And receive it on Android client:
......
HttpURLConnection urlConnection = null;
try {
URL url = new URL(request);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buffer = new byte[256];
int len = 0;
StringBuilder responseBuilder = new StringBuilder();
while ((len = in.read(buffer)) != -1) {
String str = new String(buffer, "utf-8");
responseBuilder.append(str);
}
String response = responseBuilder.toString().trim();
The response variable was written with value:
[{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"displayName":"halik","pic":"3.jpg","actType":1,471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,""type":64}]":"halik","pic":"3.jpg","actType":1,471494991000,"displayName":"shark point","pic":"2.jpg","actType":1,"type":64},{"countryID":1,"locationID":5,"siteID":5,"brief":"halik","userID":0,"status":"normal","rank":0.0,"id":3,"timestamp":1471495034000,"
Which cannot be parsed as Json String correctly with obvious errors.
Most methods which return a Json String to client request work fine as I expected except this one. But this method was implemented almost exactly the same as those ones work correctly. Thus I have no idea how this happened at all. Any one got any clew please help.
You're building String the wrong way.
Try this instead:
// …
HttpURLConnection urlConnection = null;
try {
URL url = new URL(request);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
buf.write((byte) result);
result = bis.read();
}
String response = buf.toString();
// …
I have an app running on J2ME that needs to access the Instagram API. Specifically, I need to post a comment. This is a Post method. So I try to add the "text" parameter to the body of the request by using HttpConnection.setRequestProperty(), but this doesn't seem to work, as Instagram doesn't recognize that the parameter is present. I think this method is failing to write the parameter to the body of the Http request. Any idea how I can make this work in j2me?
Here's my code:
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] response = null;
HttpConnection connection = null;
String url = "";
try {
url = "https://api.instagram.com/v1/media/" + mediaId + "/comments?access_token="+InstagramAPIUtil.accessTokenTest;// POST
url = Util.urlEncodeSpaces(url);
System.out.println(url);
connection = (HttpConnection)Connector.open(url,Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("text", comment);
if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
is = connection.openInputStream();
if (is != null) {
int ch = -1;
while ((ch = is.read()) != -1) {
bos.write(ch);
}
response = bos.toByteArray();
}
System.out.println("response: "+new String(response));
System.out.println("request: "+connection.getRequestProperty("text"));
return true;
}
And here's what I'm getting back from Instagram:
{"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"Missing 'text'"}}
I have not much experience in the HTTP area, but I think you need to write to the output stream that you can get from connection. I don't see where in your code you send actual data.
HttpURLConnection c = (HttpURLConnection) new URL("").openConnection();
OutputStream out = c.getOutputStream();
InputStream in = c.getInputStream();
I am trying to fetch videos from MY OWN YouTube account, so that I get the keywords/tags for each video. I'm trying to use the most simple approach for making an authenticated call to get my videos with keywords/tags.
Here is my Java code:
String clientID = "XXXXXXXXXXXX.apps.googleusercontent.com";
String devKey = "MY-DEVELOPER-KEY";
String userEmail = "MY-GMAIL-EMAIL";
String userPassword = "MY-GMAIL-PASSWORD";
String authorName = "MY-YOUTUBE-ACCOUNT-NAME";
String url = "https://gdata.youtube.com/feeds/api/videos";
YouTubeService service = new YouTubeService( clientID, devKey );
service.setUserCredentials( userEmail, userPassword );
YouTubeQuery query = new YouTubeQuery( new URL( url ) );
query.setAuthor( authorName );
VideoFeed videoFeed = service.query( query, VideoFeed.class );
Please, help me understand what I am doing wrong, to authenticate and get those media keywords.
If you are going to refer me to another authentication option, please, show an example of using that other option for my specific scenario.
You're running into the behavior described in this blog post: your API calls are going against the search index, and those results will never have the keywords in them.
There's an example that shows how you could request the uploads feed in Java using v2 of the Data API; you can modify that example to use the channel name default instead of username and you'll automatically pull in the uploads feed for the currently authenticated account.
Here is what finally worked for me to get JSON-C feed with tags (keywords):
/** AUTHENITICATION **/
// HTTP connection
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// Form the POST parameters
StringBuilder content = new StringBuilder();
content.append("Email=").append(URLEncoder.encode("MY-GMAIL-LOGIN", "UTF-8"));
content.append("&Passwd=").append(URLEncoder.encode("MY-GMAIL-PASSWORD", "UTF-8"));
content.append("&service=").append(URLEncoder.encode("youtube", "UTF-8"));
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(content.toString().getBytes("UTF-8"));
outputStream.close();
// Check response status
int responseCode = urlConnection.getResponseCode();
if( responseCode != HttpURLConnection.HTTP_OK ) {
// EXCEPTION
}
// Get the token from the response
String token;
InputStream inputStream = urlConnection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = in.readLine()) != null) {
if ( line.indexOf("Auth=") > -1 ) {
token = line.split("=")[1];
}
}
/** JSON-C FEED WITH TAGS **/
HttpClient client = new HttpClient();
GetMethod method = new GetMethod("http://gdata.youtube.com/feeds/api/users/default/uploads?v=2&alt=jsonc&max-results=50&start-index=1");
// set the authentication headers
method.setRequestHeader("Authorization", "GoogleLogin auth=" + token);
method.setRequestHeader("X-GData-Key", "key=MY-DEV-KEY");
method.setRequestHeader("GData-Version", "2");
method.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
// Make the call
int statusCode = client.executeMethod(method);
if ( statusCode != HttpStatus.SC_OK ) {
// EXCEPTION
}
String JSON = method.getResponseBodyAsString();