Java Code Examples for java.net.HttpURLConnection

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/options/.

Source file: OptionsPackage.java

  38 
vote

public boolean loadURL(String propertiesUrl){
  try {
    URL url=new URL(propertiesUrl);
    HttpURLConnection con=(HttpURLConnection)url.openConnection();
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    properties.load(in);
    return true;
  }
 catch (  Exception e) {
    Utils.log("Properties file not found",System.err);
    return false;
  }
}
 

Example 2

From project andlytics, under directory /src/com/github/andlyticsproject/.

Source file: Main.java

  34 
vote

@Override protected Boolean doInBackground(List<AppInfo>... params){
  List<AppInfo> appInfos=params[0];
  Boolean success=false;
  for (  AppInfo appInfo : appInfos) {
    String iconUrl=appInfo.getIconUrl();
    if (iconUrl != null) {
      File iconFile=new File(getCacheDir() + "/" + appInfo.getIconName());
      if (!iconFile.exists()) {
        try {
          iconFile.createNewFile();
          URL url=new URL(iconUrl);
          HttpURLConnection c=(HttpURLConnection)url.openConnection();
          c.setRequestMethod("GET");
          c.connect();
          FileOutputStream fos=new FileOutputStream(iconFile);
          InputStream is=c.getInputStream();
          byte[] buffer=new byte[1024];
          int len1=0;
          while ((len1=is.read(buffer)) != -1) {
            fos.write(buffer,0,len1);
          }
          fos.close();
          is.close();
          success=true;
        }
 catch (        IOException e) {
          if (iconFile.exists()) {
            iconFile.delete();
          }
          Log.d("log_tag","Error: " + e);
        }
      }
    }
  }
  return success;
}
 

Example 3

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/oauth/signpost/basic/.

Source file: DefaultOAuthProvider.java

  34 
vote

protected HttpRequest createRequest(String endpointUrl) throws MalformedURLException, IOException {
  HttpURLConnection connection=(HttpURLConnection)new URL(endpointUrl).openConnection();
  connection.setRequestMethod("POST");
  connection.setAllowUserInteraction(false);
  connection.setRequestProperty("Content-Length","0");
  return new HttpURLConnectionRequestAdapter(connection);
}
 

Example 4

From project alfredo, under directory /alfredo/src/main/java/com/cloudera/alfredo/client/.

Source file: PseudoAuthenticator.java

  33 
vote

/** 
 * Performs simple authentication against the specified URL. <p/> If a token is given if does a NOP and returns the given token. <p/> If no token is given, it will perform a HTTP <code>OPTIONS</code> request injecting an additional parameter  {@link #USER_NAME} in the query string with the value returned by the {@link #getUserName()}method. <p> If the response is successful it will update the authentication token.
 * @param url the URl to authenticate against.
 * @param token the authencation token being used for the user.
 * @throws IOException if an IO error occurred.
 * @throws AuthenticationException if an authentication error occurred.
 */
@Override public void authenticate(URL url,AuthenticatedURL.Token token) throws IOException, AuthenticationException {
  String strUrl=url.toString();
  String paramSeparator=(strUrl.contains("?")) ? "&" : "?";
  strUrl+=paramSeparator + USER_NAME_EQ + getUserName();
  url=new URL(strUrl);
  HttpURLConnection conn=(HttpURLConnection)url.openConnection();
  conn.setRequestMethod("OPTIONS");
  conn.connect();
  AuthenticatedURL.extractToken(conn,token);
}
 

Example 5

From project amber, under directory /oauth-2.0/integration-tests/src/test/java/org/apache/amber/oauth2/integration/.

Source file: Common.java

  33 
vote

public static HttpURLConnection doRequest(OAuthClientRequest req) throws IOException {
  URL url=new URL(req.getLocationUri());
  HttpURLConnection c=(HttpURLConnection)url.openConnection();
  c.setInstanceFollowRedirects(true);
  c.connect();
  c.getResponseCode();
  return c;
}
 

Example 6

From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.

Source file: ConfluencePluginList.java

  33 
vote

private static HttpURLConnection connect(String url,String sessionId) throws IOException {
  HttpURLConnection huc=(HttpURLConnection)new URL(url).openConnection();
  huc.setInstanceFollowRedirects(false);
  huc.setDoOutput(false);
  if (sessionId != null)   huc.addRequestProperty("Cookie",sessionId);
  InputStream i=huc.getInputStream();
  while (i.read() >= 0)   ;
  return huc;
}
 

Example 7

From project cascading, under directory /src/hadoop/cascading/tap/hadoop/io/.

Source file: HttpFileSystem.java

  33 
vote

@Override public FSDataInputStream open(Path path,int i) throws IOException {
  URL url=makeUrl(path);
  HttpURLConnection connection=(HttpURLConnection)url.openConnection();
  connection.setRequestMethod("GET");
  connection.connect();
  debugConnection(connection);
  return new FSDataInputStream(new FSDigestInputStream(connection.getInputStream(),getMD5SumFor(getConf(),path)));
}
 

Example 8

From project activemq-apollo, under directory /apollo-openwire/src/main/scala/org/apache/activemq/apollo/openwire/support/blob/.

Source file: DefaultBlobUploadStrategy.java

  32 
vote

public void deleteFile(ActiveMQBlobMessage message) throws IOException, OpenwireException {
  URL url=createUploadURL(message);
  HttpURLConnection connection=(HttpURLConnection)url.openConnection();
  connection.setRequestMethod("DELETE");
  connection.connect();
  connection.disconnect();
  if (!isSuccessfulCode(connection.getResponseCode())) {
    throw new IOException("DELETE was not successful: " + connection.getResponseCode() + " "+ connection.getResponseMessage());
  }
}
 

Example 9

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/.

Source file: Downloader.java

  32 
vote

private static boolean exists(final String URLName) throws IOException {
  HttpURLConnection con=null;
  try {
    HttpURLConnection.setFollowRedirects(false);
    con=(HttpURLConnection)new URL(URLName).openConnection();
    con.setRequestMethod("HEAD");
    return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
  }
  finally {
    if (con != null) {
      con.disconnect();
    }
  }
}
 

Example 10

From project AlarmApp-Android, under directory /src/org/alarmapp/web/http/.

Source file: HttpUtil.java

  32 
vote

private static String get(URL url,HashMap<String,String> headers) throws WebException {
  try {
    Ensure.notNull(url);
    HttpURLConnection http=(HttpURLConnection)url.openConnection();
    http.setRequestMethod("GET");
    http.setReadTimeout(10000);
    setHeaders(http,headers);
    return getResponse(http);
  }
 catch (  IOException e) {
    throw new WebException(NOT_CONNECTED);
  }
}
 

Example 11

From project android-joedayz, under directory /Proyectos/AndroidFoursquare/src/com/mycompany/fsq/.

Source file: FoursquareApp.java

  32 
vote

private void getAccessToken(final String code){
  mProgress.setMessage("Getting access token ...");
  mProgress.show();
  new Thread(){
    @Override public void run(){
      Log.i(TAG,"Getting access token");
      int what=0;
      try {
        URL url=new URL(mTokenUrl + "&code=" + code);
        Log.i(TAG,"Opening URL " + url.toString());
        HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoInput(true);
        urlConnection.connect();
        JSONObject jsonObj=(JSONObject)new JSONTokener(streamToString(urlConnection.getInputStream())).nextValue();
        mAccessToken=jsonObj.getString("access_token");
        Log.i(TAG,"Got access token: " + mAccessToken);
      }
 catch (      Exception ex) {
        what=1;
        ex.printStackTrace();
      }
      mHandler.sendMessage(mHandler.obtainMessage(what,1,0));
    }
  }
.start();
}
 

Example 12

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/urlfetch/local/.

Source file: UrlFetchCommonHandler.java

  32 
vote

/** 
 * doFetch- the template method.
 * @see #prepareConnection(HTTPRequest) 
 * @see #configConnection(HttpURLConnection,HTTPRequest)
 * @see #resultConnection(HttpURLConnection)
 * @param request  the specified request
 * @return {@link HTTPResponse}
 * @throws IOException IOException from java.net
 */
protected HTTPResponse doFetch(final HTTPRequest request) throws IOException {
  final HttpURLConnection httpURLConnection=prepareConnection(request);
  configConnection(httpURLConnection,request);
  httpURLConnection.connect();
  final HTTPResponse ret=resultConnection(httpURLConnection);
  httpURLConnection.disconnect();
  return ret;
}
 

Example 13

From project bam, under directory /release/jbossas/tests/platform/custom_events/custom_events_tester/src/test/java/org/overlord/bam/tests/platforms/jbossas/customevents/.

Source file: JBossASCustomEventsProcessedTest.java

  32 
vote

/** 
 * This method deserializes the events into a list of hashmaps. The actual objects are not deserialized, as this would require the domain objects to be included in all deployments, which would make verifying classloading/isolation difficult.
 * @return The list of objects representing events
 * @throws Exception Failed to deserialize the events
 */
protected java.util.List<?> getEvents() throws Exception {
  java.util.List<?> ret=null;
  URL getUrl=new URL("http://localhost:8080/custom-events-monitor/monitor/events");
  HttpURLConnection connection=(HttpURLConnection)getUrl.openConnection();
  connection.setRequestMethod("GET");
  System.out.println("Content-Type: " + connection.getContentType());
  java.io.InputStream is=connection.getInputStream();
  ret=MAPPER.readValue(is,java.util.List.class);
  return (ret);
}
 

Example 14

From project BetterShop_1, under directory /src/me/jascotty2/lib/net/.

Source file: FileDownloader.java

  32 
vote

public static boolean goodLink(String location){
  try {
    HttpURLConnection.setFollowRedirects(true);
    HttpURLConnection con=(HttpURLConnection)new URL(location).openConnection();
    con.setRequestMethod("HEAD");
    return (con.getResponseCode() == HttpURLConnection.HTTP_OK || con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP);
  }
 catch (  Exception e) {
    return false;
  }
}
 

Example 15

From project brix-cms, under directory /brix-demo/src/main/java/org/brixcms/demo/web/tile/stockquote/.

Source file: StockQuoteRequest.java

  32 
vote

/** 
 * Calls the SOAP service to get the stock quote for the symbol.
 * @param symbol the name to search for
 * @return the SOAP response containing the stockquote
 */
private String getSOAPQuote(String symbol){
  String response="";
  try {
    final URL url=new URL(serviceUrl);
    final String message=createMessage(symbol);
    HttpURLConnection httpConn=setUpHttpConnection(url,message.length());
    writeRequest(message,httpConn);
    response=readResult(httpConn);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return response;
}
 

Example 16

From project Cafe, under directory /webapp/src/org/openqa/selenium/net/.

Source file: UrlChecker.java

  32 
vote

private HttpURLConnection connectToUrl(URL url) throws IOException {
  HttpURLConnection connection=(HttpURLConnection)url.openConnection();
  connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
  connection.setReadTimeout(READ_TIMEOUT_MS);
  connection.connect();
  return connection;
}
 

Example 17

From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/web/.

Source file: MultiPartFormOutputStream.java

  32 
vote

/** 
 * Creates a new <code>java.net.URLConnection</code> object from the specified <code>java.net.URL</code>. This is a convenience method which will set the <code>doInput</code>, <code>doOutput</code>, <code>useCaches</code> and <code>defaultUseCaches</code> fields to the appropriate settings in the correct order.
 * @return a <code>java.net.URLConnection</code> object for the URL
 * @throws java.io.IOException on input/output errors
 */
public static URLConnection createConnection(URL url) throws IOException {
  URLConnection urlConn=url.openConnection();
  if (urlConn instanceof HttpURLConnection) {
    HttpURLConnection httpConn=(HttpURLConnection)urlConn;
    httpConn.setRequestMethod("POST");
  }
  urlConn.setDoInput(true);
  urlConn.setDoOutput(true);
  urlConn.setUseCaches(false);
  urlConn.setDefaultUseCaches(false);
  return urlConn;
}
 

Example 18

From project chililog-server, under directory /src/test/java/org/chililog/server/pubsub/.

Source file: TestUtils.java

  32 
vote

/** 
 * Builds a HTTP connection ready for sending to server
 * @param urlString URL to send to
 * @param method HTTP method
 * @param authtoken Authentication token
 * @return HttpURLConnection
 * @throws Exception
 */
public static HttpURLConnection getHttpURLConnection(String urlString,HttpMethod method) throws Exception {
  URL url=new URL(urlString);
  HttpURLConnection conn=(HttpURLConnection)url.openConnection();
  if (method == HttpMethod.DELETE) {
    conn.setRequestMethod(method.getName());
  }
  if (method == HttpMethod.POST || method == HttpMethod.PUT) {
    conn.setDoOutput(true);
    conn.setRequestMethod(method.getName());
    conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
  }
  return conn;
}
 

Example 19

From project cicada, under directory /samples/nextbuses/src/org/cicadasong/samples/nextbuses/.

Source file: NextBuses.java

  32 
vote

@Override protected PredictionSet doInBackground(Void... params){
  HttpURLConnection connection=null;
  PredictionSet resultSet=null;
  try {
    URL url=new URL(STOP_URL);
    connection=(HttpURLConnection)url.openConnection();
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
      String response=convertStreamToString(connection.getInputStream());
      try {
        resultSet=new PredictionSet();
        JSONObject responseObj=new JSONObject(response);
        JSONArray predArray=responseObj.getJSONArray("items");
        for (int i=0; i < predArray.length(); i++) {
          JSONObject predObj=predArray.getJSONObject(i);
          resultSet.addPrediction(predObj.getString("route_id"),predObj.getInt("minutes"));
        }
      }
 catch (      JSONException e) {
        Log.e(TAG,"Error decoding response: " + response);
      }
    }
  }
 catch (  MalformedURLException e) {
    Log.e(TAG,"Malformed request URL: " + e);
  }
catch (  IOException e) {
    Log.e(TAG,"Connection error");
  }
 finally {
    if (connection != null) {
      connection.disconnect();
    }
  }
  return resultSet;
}
 

Example 20

From project cloudify, under directory /dsl/src/test/java/org/cloudifysource/dsl/.

Source file: ServiceTestUtil.java

  32 
vote

static public void validateIcon(Service service,String serviceFilePath) throws Exception {
  String icon=service.getIcon();
  if (icon.startsWith("http")) {
    HttpURLConnection connection=(HttpURLConnection)new URL(icon).openConnection();
    connection.setRequestMethod("HEAD");
    Assert.assertEquals("The icon URL cannot establish a connection",HttpURLConnection.HTTP_OK,connection.getResponseCode());
    connection.disconnect();
  }
 else {
    File iconFile=new File(serviceFilePath,service.getIcon());
    Assert.assertTrue("Icon file not found in location: " + iconFile.getAbsolutePath(),iconFile.exists());
  }
}
 

Example 21

From project com.juick.android, under directory /src/com/juick/android/.

Source file: Utils.java

  32 
vote

public static int doHttpGetRequest(String url){
  try {
    HttpURLConnection conn=(HttpURLConnection)(new URL(url)).openConnection();
    conn.setUseCaches(false);
    conn.connect();
    int status=conn.getResponseCode();
    conn.disconnect();
    return status;
  }
 catch (  Exception e) {
    Log.e("doHttpGetRequest",e.toString());
  }
  return 0;
}
 

Example 22

From project and-bible, under directory /AndBible/src/net/bible/service/common/.

Source file: CommonUtils.java

  31 
vote

public static boolean isHttpUrlAvailable(String urlString){
  HttpURLConnection connection=null;
  try {
    URL url=new URL(urlString);
    Log.d(TAG,"Opening test connection");
    connection=(HttpURLConnection)url.openConnection();
    connection.setConnectTimeout(3000);
    Log.d(TAG,"Connecting to test internet connection");
    connection.connect();
    boolean success=(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    Log.d(TAG,"Url test result for:" + urlString + " is "+ success);
    return success;
  }
 catch (  IOException e) {
    Log.i(TAG,"No internet connection");
    return false;
  }
 finally {
    if (connection != null) {
      connection.disconnect();
    }
  }
}
 

Example 23

From project androidquery, under directory /tests/src/com/androidquery/test/.

Source file: IOUtility.java

  31 
vote

public static byte[] openHttpResult(String urlPath,boolean retry) throws IOException {
  AQUtility.debug("net",urlPath);
  URL url=new URL(urlPath);
  HttpURLConnection connection=(HttpURLConnection)url.openConnection();
  connection.setUseCaches(false);
  connection.setInstanceFollowRedirects(true);
  connection.setConnectTimeout(NET_TIMEOUT);
  int code=connection.getResponseCode();
  if (code == 307 && retry) {
    String redirect=connection.getHeaderField("Location");
    return openHttpResult(redirect,false);
  }
  if (code == -1 && retry) {
    return openHttpResult(urlPath,false);
  }
  AQUtility.debug("response",code);
  if (code == -1 || code < 200 || code >= 300) {
    throw new IOException();
  }
  byte[] result=AQUtility.toBytes(connection.getInputStream());
  return result;
}
 

Example 24

From project android_7, under directory /src/org/immopoly/android/helper/.

Source file: WebHelper.java

  31 
vote

public static JSONObject getHttpsData(URL url,boolean signed,Context context) throws ImmopolyException {
  JSONObject obj=null;
  if (Settings.isOnline(context)) {
    HttpURLConnection request;
    try {
      request=(HttpURLConnection)url.openConnection();
      request.addRequestProperty("User-Agent","immopoly android client " + ImmopolyActivity.getStaticVersionInfo());
      if (signed)       OAuthData.getInstance(context).consumer.sign(request);
      request.setConnectTimeout(SOCKET_TIMEOUT);
      request.connect();
      InputStream in=new BufferedInputStream(request.getInputStream());
      String s=readInputStream(in);
      JSONTokener tokener=new JSONTokener(s);
      return new JSONObject(tokener);
    }
 catch (    JSONException e) {
      throw new ImmopolyException("Kommunikationsproblem (beim lesen der Antwort)",e);
    }
catch (    MalformedURLException e) {
      throw new ImmopolyException("Kommunikationsproblem (fehlerhafte URL)",e);
    }
catch (    OAuthMessageSignerException e) {
      throw new ImmopolyException("Kommunikationsproblem (Signierung)",e);
    }
catch (    OAuthExpectationFailedException e) {
      throw new ImmopolyException("Kommunikationsproblem (Sicherherit)",e);
    }
catch (    OAuthCommunicationException e) {
      throw new ImmopolyException("Kommunikationsproblem (Sicherherit)",e);
    }
catch (    IOException e) {
      throw new ImmopolyException("Kommunikationsproblem",e);
    }
  }
 else   throw new ImmopolyException("Kommunikationsproblem (Offline)");
}
 

Example 25

From project android_external_oauth, under directory /core/src/main/java/net/oauth/client/.

Source file: URLConnectionResponse.java

  31 
vote

/** 
 * Return a complete description of the HTTP exchange. 
 */
@Override public void dump(Map<String,Object> into) throws IOException {
  super.dump(into);
{
    StringBuilder request=new StringBuilder(requestHeaders);
    request.append(EOL);
    if (requestExcerpt != null) {
      request.append(new String(requestExcerpt,requestEncoding));
    }
    into.put(REQUEST,request.toString());
  }
{
    HttpURLConnection http=(connection instanceof HttpURLConnection) ? (HttpURLConnection)connection : null;
    StringBuilder response=new StringBuilder();
    String value;
    for (int i=0; (value=connection.getHeaderField(i)) != null; ++i) {
      String name=connection.getHeaderFieldKey(i);
      if (i == 0 && name != null && http != null) {
        String firstLine="HTTP " + getStatusCode();
        String message=http.getResponseMessage();
        if (message != null) {
          firstLine+=(" " + message);
        }
        response.append(firstLine).append(EOL);
      }
      if (name != null) {
        response.append(name).append(": ");
        name=name.toLowerCase();
      }
      response.append(value).append(EOL);
    }
    response.append(EOL);
    if (body != null) {
      response.append(new String(((ExcerptInputStream)body).getExcerpt(),getContentCharset()));
    }
    into.put(HttpMessage.RESPONSE,response.toString());
  }
}
 

Example 26

From project AntiCheat, under directory /src/main/java/net/h31ix/anticheat/util/.

Source file: PastebinReport.java

  31 
vote

private void postReport(){
  try {
    URL urls=new URL("http://pastebin.com/api/api_post.php");
    HttpURLConnection conn=(HttpURLConnection)urls.openConnection();
    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);
    conn.setRequestMethod("POST");
    conn.addRequestProperty("Content-type","application/x-www-form-urlencoded");
    conn.setInstanceFollowRedirects(false);
    conn.setDoOutput(true);
    OutputStream out=conn.getOutputStream();
    out.write(("api_option=paste" + "&api_dev_key=" + URLEncoder.encode("c0616def494dcb5b7632304f8c52c0f1","utf-8") + "&api_paste_code="+ URLEncoder.encode(report.toString(),"utf-8")+ "&api_paste_private="+ URLEncoder.encode("0","utf-8")+ "&api_paste_name="+ URLEncoder.encode("","utf-8")+ "&api_paste_expire_date="+ URLEncoder.encode("1D","utf-8")+ "&api_paste_format="+ URLEncoder.encode("text","utf-8")+ "&api_user_key="+ URLEncoder.encode("","utf-8")).getBytes());
    out.flush();
    out.close();
    if (conn.getResponseCode() == 200) {
      InputStream receive=conn.getInputStream();
      BufferedReader reader=new BufferedReader(new InputStreamReader(receive));
      String line;
      StringBuffer response=new StringBuffer();
      while ((line=reader.readLine()) != null) {
        response.append(line);
        response.append("\r\n");
      }
      reader.close();
      String result=response.toString().trim();
      if (!result.contains("http://")) {
        url="Failed to post.  Check report.txt";
      }
 else {
        url=result.trim();
      }
    }
 else {
      url="Failed to post.  Check report.txt";
    }
  }
 catch (  Exception e) {
    url="Failed to post.  Check report.txt";
  }
}
 

Example 27

From project apg, under directory /src/org/thialfihar/android/apg/.

Source file: HkpKeyServer.java

  31 
vote

private String query(String request) throws QueryException, HttpError {
  InetAddress ips[];
  try {
    ips=InetAddress.getAllByName(mHost);
  }
 catch (  UnknownHostException e) {
    throw new QueryException(e.toString());
  }
  for (int i=0; i < ips.length; ++i) {
    try {
      String url="http://" + ips[i].getHostAddress() + ":"+ mPort+ request;
      URL realUrl=new URL(url);
      HttpURLConnection conn=(HttpURLConnection)realUrl.openConnection();
      conn.setConnectTimeout(5000);
      conn.setReadTimeout(25000);
      conn.connect();
      int response=conn.getResponseCode();
      if (response >= 200 && response < 300) {
        return readAll(conn.getInputStream(),conn.getContentEncoding());
      }
 else {
        String data=readAll(conn.getErrorStream(),conn.getContentEncoding());
        throw new HttpError(response,data);
      }
    }
 catch (    MalformedURLException e) {
    }
catch (    IOException e) {
    }
  }
  throw new QueryException("querying server(s) for '" + mHost + "' failed");
}
 

Example 28

From project apps-for-android, under directory /Translate/src/com/beust/android/translate/.

Source file: Translate.java

  31 
vote

/** 
 * Forms an HTTP request and parses the response for a translation.
 * @param text The String to translate.
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text,String from,String to) throws Exception {
  try {
    StringBuilder url=new StringBuilder();
    url.append(URL_STRING).append(from).append("%7C").append(to);
    url.append(TEXT_VAR).append(URLEncoder.encode(text,ENCODING));
    Log.d(TranslateService.TAG,"Connecting to " + url.toString());
    HttpURLConnection uc=(HttpURLConnection)new URL(url.toString()).openConnection();
    uc.setDoInput(true);
    uc.setDoOutput(true);
    try {
      Log.d(TranslateService.TAG,"getInputStream()");
      InputStream is=uc.getInputStream();
      String result=toString(is);
      JSONObject json=new JSONObject(result);
      return ((JSONObject)json.get("responseData")).getString("translatedText");
    }
  finally {
      uc.getInputStream().close();
      if (uc.getErrorStream() != null)       uc.getErrorStream().close();
    }
  }
 catch (  Exception ex) {
    throw ex;
  }
}
 

Example 29

From project arquillian-container-openshift, under directory /openshift-express/src/main/java/org/jboss/arquillian/container/openshift/express/.

Source file: OpenShiftExpressContainer.java

  31 
vote

private boolean isUrlPresent(String url){
  HttpURLConnection httpConnection=null;
  try {
    URLConnection connection=new URL(url).openConnection();
    if (!(connection instanceof HttpURLConnection)) {
      throw new IllegalStateException("Not an http connection! " + connection);
    }
    httpConnection=(HttpURLConnection)connection;
    httpConnection.setUseCaches(false);
    httpConnection.setDefaultUseCaches(false);
    httpConnection.setDoInput(true);
    httpConnection.setRequestMethod("GET");
    httpConnection.setDoOutput(false);
    httpConnection.connect();
    httpConnection.getResponseCode();
    if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
      return true;
    }
    return false;
  }
 catch (  IOException e) {
    e.printStackTrace();
    return false;
  }
 finally {
    if (httpConnection != null) {
      httpConnection.disconnect();
    }
  }
}
 

Example 30

From project babel, under directory /src/babel/util/dict/.

Source file: GoogleDictionaryCollector.java

  31 
vote

/** 
 * Forms an HTTP request, sends it using GET method and returns the result of the request as a JSONObject.
 * @param url the URL to query for a JSONObject.
 */
protected JSONObject retrieveJSON(final URL url) throws Exception {
  try {
    final HttpURLConnection uc=(HttpURLConnection)url.openConnection();
    uc.setRequestProperty("referer",m_referrer);
    uc.setRequestMethod("GET");
    uc.setDoOutput(true);
    try {
      String result=inputStreamToString(uc.getInputStream());
      result=result.substring(result.indexOf('{'),result.lastIndexOf('}') + 1);
      return new JSONObject(result);
    }
  finally {
      uc.getInputStream().close();
      if (uc.getErrorStream() != null) {
        uc.getErrorStream().close();
      }
    }
  }
 catch (  Exception ex) {
    throw new Exception("Error retrieving detection result : " + ex.toString(),ex);
  }
}
 

Example 31

From project BazaarUtils, under directory /src/com/congenialmobile/utils/.

Source file: BazaarUtils.java

  31 
vote

/** 
 * @param packageName
 * @return versionCode of the latest version on Bazaar, or -1 if not found
 * @throws IOException
 */
public static long getLatestVersionCodeOnBazaar(String packageName) throws IOException {
  URL url=new URL(URLPREFIX_CAFEBAZAAR_VERSION + URLEncoder.encode(packageName));
  HttpURLConnection connection=(HttpURLConnection)url.openConnection();
  connection.setConnectTimeout(20000);
  connection.setReadTimeout(20000);
  connection.addRequestProperty("Cache-Control","no-cache,max-age=0");
  connection.addRequestProperty("Pragma","no-cache");
  int responseCode=connection.getResponseCode();
  if (responseCode == HttpURLConnection.HTTP_OK) {
    InputStream is=connection.getInputStream();
    Scanner sc=new Scanner(is);
    return sc.nextLong();
  }
 else {
    if (DEBUG_BAZAARUTILS)     Log.w(TAG,"HTTPError for " + packageName + ": "+ responseCode);
  }
  return -1;
}
 

Example 32

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.

Source file: CustomFonts.java

  31 
vote

private static void loadRemoteFont(Context context){
  try {
    String path="http://static.beintoo.com/sdk/android/font/" + fontName;
    String sdState=android.os.Environment.getExternalStorageState();
    File fontDir;
    String fontFilePath;
    if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
      File sdDir=android.os.Environment.getExternalStorageDirectory();
      fontDir=new File(sdDir,".beintoo/fonts/");
      fontFilePath=fontDir + "/" + fontName;
    }
 else {
      fontDir=new File(context.getCacheDir(),".beintoo/fonts/");
      fontFilePath=fontDir + "/" + fontName;
    }
    if (!fontDir.exists())     fontDir.mkdirs();
    URL u=new URL(path);
    HttpURLConnection c=(HttpURLConnection)u.openConnection();
    c.setRequestMethod("GET");
    c.setDoInput(true);
    c.connect();
    FileOutputStream f=new FileOutputStream(new File(fontFilePath));
    InputStream in=c.getInputStream();
    byte[] buffer=new byte[1024];
    int len1=0;
    while ((len1=in.read(buffer)) > 0) {
      f.write(buffer,0,len1);
    }
    f.close();
    DebugUtility.showLog("Downloaded font: " + path);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 33

From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/pubchem/.

Source file: PubchemStructureGenerator.java

  31 
vote

/** 
 * submit the  {@link #requestDocument} ({@link Document}). 
 */
private final void request() throws IOException, SAXException, ParserConfigurationException, FactoryConfigurationError, DOMException, TransformerException {
  debug("submit request");
  URL server=new URL(url);
  HttpURLConnection connection=(HttpURLConnection)server.openConnection();
  connection.setRequestMethod("POST");
  connection.setRequestProperty("Content-Type","text/xml; charset=\"utf-8\"");
  connection.setDoOutput(true);
  OutputStreamWriter out=new OutputStreamWriter(connection.getOutputStream(),"UTF8");
  out.write(getXMLString(this.requestDocument));
  out.close();
  this.responseDocument=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(connection.getInputStream());
  try {
    this.requestid=xpath(ID_xpath,responseDocument).getFirstChild().getNodeValue();
  }
 catch (  Exception e) {
  }
}
 

Example 34

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.

Source file: Utils.java

  31 
vote

/** 
 * Given a URL, get an image and return as a byte array.
 * @param urlText			Image file URL
 * @return	Downloaded byte[]
 */
static public byte[] getBytesFromUrl(String urlText){
  URL u;
  try {
    u=new URL(urlText);
  }
 catch (  MalformedURLException e) {
    Logger.logError(e);
    return null;
  }
  HttpURLConnection c;
  InputStream in=null;
  try {
    c=(HttpURLConnection)u.openConnection();
    c.setConnectTimeout(30000);
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    in=c.getInputStream();
  }
 catch (  IOException e) {
    Logger.logError(e);
    return null;
  }
  ByteArrayOutputStream f=new ByteArrayOutputStream();
  try {
    byte[] buffer=new byte[1024];
    int len1=0;
    while ((len1=in.read(buffer)) > 0) {
      f.write(buffer,0,len1);
    }
    f.close();
  }
 catch (  IOException e) {
    Logger.logError(e);
    return null;
  }
  return f.toByteArray();
}
 

Example 35

From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/wsht/.

Source file: WSHTClient.java

  31 
vote

private Node makeWSHTSOAPRequest(String request) throws IOException, ParserConfigurationException, SAXException {
  HttpURLConnection con=(HttpURLConnection)wsHtEndpoint.openConnection();
  con.setRequestMethod("POST");
  con.setRequestProperty("Authorization","Basic " + getAuthorizationRealm());
  con.setRequestProperty("Content-Type","text/xml; charset=utf-8");
  con.setRequestProperty("Accept","application/soap+xml, text/xml");
  con.setDoOutput(true);
  con.setDoInput(true);
  con.connect();
  OutputStream out=con.getOutputStream();
  String soapMessage=soapCreator.createSOAP(request);
  out.write(soapMessage.getBytes("UTF-8"));
  out.close();
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  dbf.setNamespaceAware(true);
  DocumentBuilder db=dbf.newDocumentBuilder();
  Document document=db.parse(con.getInputStream());
  Node soapBody=document.getElementsByTagNameNS(NAMESPACE_SOAP,"Body").item(0);
  return soapBody.getFirstChild();
}
 

Example 36

From project c10n, under directory /core/src/test/java/c10n/resources/.

Source file: ExternalResourceTest.java

  31 
vote

private HttpServer serveTextOverHttp(final String text,String path,int port) throws IOException {
  HttpServer httpServer=HttpServer.create(new InetSocketAddress(port),0);
  HttpHandler handler=new HttpHandler(){
    @Override public void handle(    HttpExchange exchange) throws IOException {
      byte[] response=text.getBytes();
      exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK,response.length);
      exchange.getResponseBody().write(response);
      exchange.close();
    }
  }
;
  httpServer.createContext(path,handler);
  return httpServer;
}
 

Example 37

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/util/.

Source file: HttpClient.java

  31 
vote

public boolean isValidEndPoint(final URL url){
  HttpURLConnection connection=null;
  InputStream is=null;
  try {
    connection=(HttpURLConnection)url.openConnection();
    connection.setConnectTimeout(this.connectionTimeout);
    connection.setReadTimeout(this.readTimeout);
    connection.setInstanceFollowRedirects(this.followRedirects);
    connection.connect();
    final int responseCode=connection.getResponseCode();
    for (    final int acceptableCode : this.acceptableCodes) {
      if (responseCode == acceptableCode) {
        if (log.isDebugEnabled()) {
          log.debug("Response code from server matched " + responseCode + ".");
        }
        return true;
      }
    }
    if (log.isDebugEnabled()) {
      log.debug("Response Code did not match any of the acceptable response codes.  Code returned was " + responseCode);
    }
    if (responseCode == 500) {
      is=connection.getInputStream();
      final String value=IOUtils.toString(is);
      log.error(String.format("There was an error contacting the endpoint: %s; The error was:\n%s",url.toExternalForm(),value));
    }
  }
 catch (  final IOException e) {
    log.error(e.getMessage(),e);
  }
 finally {
    IOUtils.closeQuietly(is);
    if (connection != null) {
      connection.disconnect();
    }
  }
  return false;
}
 

Example 38

From project caustic, under directory /implementation/javanet/src/net/caustic/http/.

Source file: JavaNetHttpRequester.java

  31 
vote

/** 
 * Request a  {@link HttpURLConnection}, and follow any redirects while adding cookies.
 * @param method The {@link Method} to use.
 * @param urlStr A URL to load.  Also defaults to be the Referer in the request header.
 * @param headers A {@link Hashtable} of additional headers.
 * @param encodedPostData A {@link String} of post data to send, already encoded.
 * @return A {@link HttpResponse}.
 */
private HttpResponse getResponse(String method,String urlStr,Hashtable requestHeaders,String encodedPostData) throws HttpRequestException {
  HttpURLConnection.setFollowRedirects(false);
  try {
    HttpURLConnection conn=(HttpURLConnection)(new URL(urlStr)).openConnection();
    Enumeration<String> headerNames=requestHeaders.keys();
    while (headerNames.hasMoreElements()) {
      String headerName=(String)headerNames.nextElement();
      String headerValue=(String)requestHeaders.get(headerName);
      conn.setRequestProperty(headerName,headerValue);
    }
    conn.setDoInput(true);
    conn.setReadTimeout(timeoutMilliseconds);
    if (method.equalsIgnoreCase(HttpBrowser.POST)) {
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      OutputStreamWriter writer=new OutputStreamWriter(conn.getOutputStream());
      writer.write(encodedPostData);
      writer.flush();
    }
 else {
      conn.setRequestMethod(method.toUpperCase());
    }
    return new JavaNetHttpResponse(conn);
  }
 catch (  IOException e) {
    throw new HttpRequestException(e.getMessage());
  }
}
 

Example 39

From project ceylon-module-resolver, under directory /impl/src/main/java/com/redhat/ceylon/cmr/impl/.

Source file: RemoteContentStore.java

  31 
vote

protected InputStream openStream(final URL url) throws IOException {
  final URLConnection conn=url.openConnection();
  if (conn instanceof HttpURLConnection) {
    HttpURLConnection huc=(HttpURLConnection)conn;
    addCredentials(huc);
    InputStream stream=conn.getInputStream();
    int code=huc.getResponseCode();
    if (code != -1 && code != 200) {
      log.info("Got " + code + " for url: "+ url);
      return null;
    }
    log.debug("Got " + code + " for url: "+ url);
    return stream;
  }
  return null;
}
 

Example 40

From project Clotho-Core, under directory /ClothoApps/SequenceChecker/src/org/clothocad/tool/sequencechecker/.

Source file: SeqCheckController.java

  31 
vote

protected String fetchConstructSequence(String constructID){
  InputStream inputStream=null;
  URL url=null;
  HttpURLConnection connection=null;
  String seq="";
  if (constructID != null && constructID.length() > 0) {
    try {
      url=new URL(_webServiceBaseUrl + "?id=" + constructID+ "&format=seq");
      inputStream=url.openStream();
      seq=new Scanner(inputStream).useDelimiter("\\A").next();
    }
 catch (    MalformedURLException ex) {
      Exceptions.printStackTrace(ex);
    }
catch (    IOException ex) {
      Exceptions.printStackTrace(ex);
    }
 finally {
      try {
        if (inputStream != null) {
          inputStream.close();
        }
      }
 catch (      IOException ex) {
        Exceptions.printStackTrace(ex);
      }
    }
  }
  return seq;
}
 

Example 41

From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/api/.

Source file: BeesClient.java

  31 
vote

/** 
 * The actual engine behind the REST API call. It sends a request in JSON and expects a JSON response back. Note that for historical reasons, there's the other half of the API that uses query parameters + digital signing.
 * @param apiTail The end point to hit. Appended to  {@link #base}. Shouldn't start with '/'
 * @param request JSON-bound POJO object that represents the request payload, or null if none.
 * @param type JSON-bound POJO class to unmarshal the response into.
 * @param method HTTP method name like GET or POST.
 * @throws IOException If the communication fails.
 */
<T>T postAndRetrieve(String apiTail,Object request,Class<T> type,String method) throws IOException {
  URL url=new URL(base,apiTail);
  HttpURLConnection uc=(HttpURLConnection)url.openConnection();
  uc.setRequestProperty("Authorization","Basic " + encodedAccountAuthorization);
  uc.setRequestProperty("Content-type","application/json");
  uc.setRequestProperty("Accept","application/json");
  uc.setRequestMethod(method);
  if (request != null) {
    uc.setDoOutput(true);
    MAPPER.writeValue(uc.getOutputStream(),request);
    uc.getOutputStream().close();
  }
  uc.connect();
  try {
    InputStreamReader r=new InputStreamReader(uc.getInputStream(),"UTF-8");
    String data=IOUtils.toString(r);
    if (type == null) {
      return null;
    }
    T ret=MAPPER.readValue(data,type);
    if (ret instanceof CBObject)     ((CBObject)ret).root=this;
    return ret;
  }
 catch (  IOException e) {
    String rsp="";
    InputStream err=uc.getErrorStream();
    if (err != null) {
      try {
        rsp=IOUtils.toString(err);
      }
 catch (      IOException _) {
      }
    }
    throw (IOException)new IOException("Failed to POST to " + url + " : code="+ uc.getResponseCode()+ " response="+ rsp).initCause(e);
  }
}
 

Example 42

From project cogroo4, under directory /lang/pt_br/cogroo-addon/src/org/cogroo/addon/dialogs/reporterror/.

Source file: Login.java

  31 
vote

private static void request(boolean quiet,String method,java.net.URL url,Map<String,String> body) throws IOException {
  if (LOGGER.isLoggable(Level.FINE)) {
    LOGGER.log(Level.FINE,"[issuing request: " + method + " "+ url+ "]");
  }
  HttpURLConnection connection=(HttpURLConnection)url.openConnection();
  connection.setRequestMethod(method);
  if (body != null) {
    connection.setDoOutput(true);
    OutputStream output=connection.getOutputStream();
    DataOutputStream out2=new DataOutputStream(output);
    out2.writeBytes(convert(body));
  }
  long time=System.currentTimeMillis();
  connection.connect();
  connection.disconnect();
  time=System.currentTimeMillis() - time;
  if (!quiet) {
    String header=null;
    String headerValue=null;
    int index=0;
    while ((headerValue=connection.getHeaderField(index)) != null) {
      header=connection.getHeaderFieldKey(index);
      if (header == null) {
        System.out.println(headerValue);
      }
 else {
        System.out.println(header + ": " + headerValue);
      }
      index++;
    }
  }
}
 

Example 43

From project avro, under directory /lang/java/ipc/src/main/java/org/apache/avro/ipc/.

Source file: HttpTransceiver.java

  30 
vote

public synchronized void writeBuffers(List<ByteBuffer> buffers) throws IOException {
  if (proxy == null)   connection=(HttpURLConnection)url.openConnection();
 else   connection=(HttpURLConnection)url.openConnection(proxy);
  connection.setRequestMethod("POST");
  connection.setRequestProperty("Content-Type",CONTENT_TYPE);
  connection.setRequestProperty("Content-Length",Integer.toString(getLength(buffers)));
  connection.setDoOutput(true);
  connection.setReadTimeout(timeout);
  connection.setConnectTimeout(timeout);
  OutputStream out=connection.getOutputStream();
  try {
    writeBuffers(buffers,out);
  }
  finally {
    out.close();
  }
}
 

Example 44

From project activejdbc, under directory /javalite-common/src/main/java/org/javalite/http/.

Source file: Request.java

  29 
vote

public Request(String url,int connectTimeout,int readTimeout){
  try {
    this.url=url;
    connection=(HttpURLConnection)new URL(url).openConnection();
    connection.setConnectTimeout(connectTimeout);
    connection.setReadTimeout(readTimeout);
  }
 catch (  Exception e) {
    throw new HttpException("Failed URL: " + url,e);
  }
}
 

Example 45

From project aether-core, under directory /aether-connector-asynchttpclient/src/main/java/org/eclipse/aether/connector/async/.

Source file: AsyncRepositoryConnector.java

  29 
vote

private void handleResponseCode(String url,int responseCode,String responseMsg) throws AuthorizationException, ResourceDoesNotExistException, TransferException {
  if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
    throw new ResourceDoesNotExistException(String.format("Unable to locate resource %s. Error code %s",url,responseCode));
  }
  if (responseCode == HttpURLConnection.HTTP_FORBIDDEN || responseCode == HttpURLConnection.HTTP_UNAUTHORIZED || responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
    throw new AuthorizationException(String.format("Access denied to %s. Error code %s, %s",url,responseCode,responseMsg));
  }
  if (responseCode >= HttpURLConnection.HTTP_MULT_CHOICE) {
    throw new TransferException(String.format("Failed to transfer %s. Error code %s, %s",url,responseCode,responseMsg));
  }
}
 

Example 46

From project agraph-java-client, under directory /src/com/franz/agraph/http/.

Source file: AGHTTPClient.java

  29 
vote

public void post(String url,Header[] headers,NameValuePair[] params,RequestEntity requestEntity,AGResponseHandler handler) throws AGHttpException {
  PostMethod post=new PostMethod(url);
  setDoAuthentication(post);
  for (  Header header : headers) {
    post.addRequestHeader(header);
  }
  post.addRequestHeader("Accept-encoding","gzip");
  post.setQueryString(params);
  if (requestEntity != null) {
    post.setRequestEntity(requestEntity);
  }
  try {
    int httpCode=getHttpClient().executeMethod(post);
    if (httpCode == HttpURLConnection.HTTP_OK) {
      if (handler != null)       handler.handleResponse(post);
    }
 else     if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
      throw new AGHttpException(new UnauthorizedException());
    }
 else     if (!is2xx(httpCode)) {
      AGErrorHandler errHandler=new AGErrorHandler();
      errHandler.handleResponse(post);
      throw errHandler.getResult();
    }
  }
 catch (  HttpException e) {
    throw new AGHttpException(e);
  }
catch (  IOException e) {
    handleSessionConnectionError(e,url);
  }
 finally {
    if (handler == null || handler.releaseConnection()) {
      releaseConnection(post);
    }
  }
}
 

Example 47

From project Airports, under directory /src/com/nadmm/airports/notams/.

Source file: NotamService.java

  29 
vote

private void fetchNotams(String icaoCode,File notamFile) throws IOException {
  InputStream in=null;
  String params=String.format(NOTAM_PARAM,icaoCode);
  HttpsURLConnection conn=(HttpsURLConnection)NOTAM_URL.openConnection();
  conn.setRequestProperty("Connection","close");
  conn.setDoInput(true);
  conn.setDoOutput(true);
  conn.setUseCaches(false);
  conn.setConnectTimeout(30 * 1000);
  conn.setReadTimeout(30 * 1000);
  conn.setRequestMethod("POST");
  conn.setRequestProperty("User-Agent","Mozilla/5.0 (X11; U; Linux i686; en-US)");
  conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  conn.setRequestProperty("Content-Length",Integer.toString(params.length()));
  OutputStream faa=conn.getOutputStream();
  faa.write(params.getBytes("UTF-8"));
  faa.close();
  int response=conn.getResponseCode();
  if (response == HttpURLConnection.HTTP_OK) {
    in=conn.getInputStream();
    ArrayList<String> notams=parseNotamsFromHtml(in);
    in.close();
    BufferedOutputStream cache=new BufferedOutputStream(new FileOutputStream(notamFile));
    for (    String notam : notams) {
      cache.write(notam.getBytes());
      cache.write('\n');
    }
    cache.close();
  }
}
 

Example 48

From project Android, under directory /app/src/main/java/com/github/mobile/accounts/.

Source file: AccountClient.java

  29 
vote

@Override protected HttpURLConnection configureRequest(final HttpURLConnection request){
  GitHubAccount account=accountProvider.get();
  if (Log.isLoggable(TAG,DEBUG))   Log.d(TAG,"Authenticating using " + account);
  String token=account.getAuthToken();
  if (!TextUtils.isEmpty(token))   setOAuth2Token(token);
 else   setCredentials(account.getUsername(),account.getPassword());
  return super.configureRequest(request);
}
 

Example 49

From project android-xbmcremote, under directory /src/org/xbmc/android/remote/presentation/wizard/setupwizard/.

Source file: SetupWizardPageLogin.java

  29 
vote

private void testConnection(){
  IInfoManager info=ManagerFactory.getInfoManager(new INotifiableController(){
    public void runOnUI(    Runnable action){
      mHandler.post(action);
    }
    public void onWrongConnectionState(    int state,    INotifiableManager manager,    Command<?> source){
    }
    public void onMessage(    String message){
    }
    public void onError(    Exception e){
      if (e instanceof HttpException && e.getMessage().equals(HttpURLConnection.HTTP_UNAUTHORIZED)) {
        errorMsg.setText(R.string.setup_wizard_login_wrong);
      }
    }
  }
);
  info.getSystemInfo(new DataResponse<String>(){
    @Override public void run(){
      if (value != null && !value.equals("")) {
        showNextPage();
      }
    }
  }
,SystemInfo.SYSTEM_BUILD_VERSION,getContext());
}
 

Example 50

From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/reporter/.

Source file: PostReporter.java

  29 
vote

/** 
 * Executes the given request as a HTTP POST action.
 * @param url the url
 * @param params the parameter
 * @return the response as a String.
 * @throws IOException if the server cannot be reached
 */
public static void post(URL url,String params) throws IOException {
  URLConnection conn=url.openConnection();
  if (conn instanceof HttpURLConnection) {
    ((HttpURLConnection)conn).setRequestMethod("POST");
    conn.setRequestProperty("Content-Type","application/json");
  }
  OutputStreamWriter writer=null;
  try {
    conn.setDoOutput(true);
    writer=new OutputStreamWriter(conn.getOutputStream(),Charset.forName("UTF-8"));
    writer.write(params);
    writer.flush();
  }
  finally {
    if (writer != null) {
      writer.close();
    }
  }
}
 

Example 51

From project apb, under directory /modules/apb-base/src/apb/tasks/.

Source file: DownloadTask.java

  29 
vote

private void download() throws IOException {
  URLConnection c=getConnection();
  c.connect();
  if (c instanceof HttpURLConnection) {
    if (((HttpURLConnection)c).getResponseCode() == HTTP_UNAUTHORIZED) {
      throw new BuildException("HTTP Authorization failure");
    }
  }
  InputStream is=openInputStream(c);
  if (is == null) {
    env.handle("Can not download " + source + " to "+ dest);
  }
 else {
    download(is,c.getContentLength());
  }
}
 

Example 52

From project apjp, under directory /APJP_REMOTE_JAVA_APPENGINE/src/main/java/APJP/HTTP11/.

Source file: HTTPRequest.java

  29 
vote

public void open() throws HTTPRequestException {
  try {
    HTTPMessageHeader httpRequestMessage1Header1=httpRequestMessage.getHTTPMessageHeader("");
    String httpRequestMessage1Header1Value1=httpRequestMessage1Header1.getValue();
    String[] httpRequestMessage1Header1Values1=httpRequestMessage1Header1Value1.split(" ");
    String httpRequestMessage1Header1Value2=httpRequestMessage1Header1Values1[0];
    String httpRequestMessage1Header1Value3=httpRequestMessage1Header1Values1[1];
    HTTPMessageHeader httpRequestMessage1Header2=httpRequestMessage.getHTTPMessageHeader("Host");
    String httpRequestMessage1Header2Value1=httpRequestMessage1Header2.getValue();
    httpURL=new URL("http://" + httpRequestMessage1Header2Value1 + httpRequestMessage1Header1Value3);
    httpURLConnection=(HttpURLConnection)httpURL.openConnection();
    httpURLConnection.setConnectTimeout(5000);
    httpURLConnection.setReadTimeout(55000);
    httpURLConnection.setInstanceFollowRedirects(false);
    if (httpRequestMessage1Header1Value2.equalsIgnoreCase("POST") || httpRequestMessage1Header1Value2.equalsIgnoreCase("PUT")) {
      httpURLConnection.setDoOutput(true);
    }
    httpURLConnection.setDoInput(true);
    httpURLConnection.setRequestMethod(httpRequestMessage1Header1Value2);
    HTTPMessageHeader[] httpRequestMessage1Headers3=httpRequestMessage.getHTTPMessageHeaders();
    for (    HTTPMessageHeader httpRequestMessage1Header3 : httpRequestMessage1Headers3) {
      String httpRequestMessage1Header3Key1=httpRequestMessage1Header3.getKey();
      String httpRequestMessage1Header3Value1=httpRequestMessage1Header3.getValue();
      httpURLConnection.setRequestProperty(httpRequestMessage1Header3Key1,httpRequestMessage1Header3Value1);
    }
    if (httpURLConnection.getDoOutput()) {
      OutputStream httpRequestOutputStream=httpURLConnection.getOutputStream();
      httpRequestMessage.read(httpRequestOutputStream);
    }
    httpURLConnection.connect();
  }
 catch (  Exception e) {
    throw new HTTPRequestException("HTTP_REQUEST/OPEN",e);
  }
}
 

Example 53

From project arquillian-container-tomcat, under directory /tomcat-common/src/main/java/org/jboss/arquillian/container/tomcat/.

Source file: CommonTomcatManager.java

  29 
vote

protected void processResponse(String command,HttpURLConnection hconn) throws IOException {
  int httpResponseCode=hconn.getResponseCode();
  if (httpResponseCode >= 400 && httpResponseCode < 500) {
    throw new ConfigurationException("Unable to connect to Tomcat manager. " + "The server command (" + command + ") failed with responseCode ("+ httpResponseCode+ ") and responseMessage ("+ hconn.getResponseMessage()+ ").\n\n"+ "Please make sure that you provided correct credentials to an user which is able to access Tomcat manager application.\n"+ "These credentials can be specified in the Arquillian container configuration as \"user\" and \"pass\" properties.\n"+ "The user must have appripriate role specified in tomcat-users.xml file.\n");
  }
 else   if (httpResponseCode >= 300) {
    throw new IllegalStateException("The server command (" + command + ") failed with responseCode ("+ httpResponseCode+ ") and responseMessage ("+ hconn.getResponseMessage()+ ").");
  }
  BufferedReader reader=null;
  try {
    reader=new BufferedReader(new InputStreamReader(hconn.getInputStream(),MANAGER_CHARSET));
    String line=reader.readLine();
    String contentError=null;
    if (line != null && !line.startsWith("OK -")) {
      contentError=line;
    }
    while (line != null) {
      if (log.isLoggable(Level.FINE)) {
        log.fine(line);
      }
      line=reader.readLine();
    }
    if (contentError != null) {
      throw new RuntimeException("The server command (" + command + ") failed with content ("+ contentError+ ").");
    }
  }
  finally {
    IOUtil.closeQuietly(reader);
  }
}
 

Example 54

From project caseconductor-platform, under directory /utest-webservice/utest-webservice-impl/src/main/java/com/utest/webservice/auth/.

Source file: BasicAuthAuthorizationInterceptor.java

  29 
vote

@Override public void handleMessage(final Message message) throws Fault {
  try {
    AuthorizationPolicy policy=message.get(AuthorizationPolicy.class);
    Authentication authentication=SessionUtil.getAuthenticationToken(message);
    if (policy == null && authentication == null) {
      sendErrorResponse(message,HttpURLConnection.HTTP_UNAUTHORIZED);
      return;
    }
    if (authentication == null) {
      authentication=new UsernamePasswordAuthenticationToken(policy.getUserName(),policy.getPassword());
      ((UsernamePasswordAuthenticationToken)authentication).setDetails(message.get("HTTP.REQUEST"));
      authentication=authenticationProvider.authenticate(authentication);
    }
 else {
      if (((UsernamePasswordAuthenticationToken)authentication).getDetails() == null) {
        ((UsernamePasswordAuthenticationToken)authentication).setDetails(message.get("HTTP.REQUEST"));
      }
    }
    SecurityContextHolder.getContext().setAuthentication(authentication);
  }
 catch (  final RuntimeException ex) {
    sendErrorResponse(message,HttpURLConnection.HTTP_UNAUTHORIZED);
    throw ex;
  }
}
 

Example 55

From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/network/.

Source file: DownloadHandler.java

  29 
vote

/** 
 * Download the content for the given  {@linkplain HttpURLConnection connection}. The numberOfRetries defines the number of attends if the network timeout is reach. Return the response as a String.
 * @throws IOException if failed to read the downloaded content
 * @throws NetworkConnectionException if download timeout due to network connection issue
 * @throws InvalidUrlException if the given URL is not valid
 */
public static String getResponse(HttpURLConnection connection,int numberOfRetries) throws IOException, InvalidUrlException, NetworkConnectionException {
  startConnect(connection,numberOfRetries);
  InputStream inputStream=connection.getInputStream();
  StringBuilder response=new StringBuilder();
  int size;
  byte[] buffer=new byte[BUFFER_SIZE];
  while ((size=inputStream.read(buffer)) != -1) {
    response.append(new String(buffer,0,size));
  }
  connection.disconnect();
  return response.toString();
}