HttpClientでMixiにログインするサンプルプログラムの実行に失敗する理由

このQ&Aのポイント
  • Eclipse上でHttpClientのライブラリをダウンロードし、Mixiにログインするサンプルプログラムを実行しようとしたが、PostMethodとGetMethodの型解決エラーが発生した。
  • ダウンロードしたファイルには必要なライブラリ(commons-codec、commons-logging、httpclient、httpclient-cache、httpcore、hhtpmime)が全て含まれており、パスも通しているが、他にも必要なライブラリはあるのだろうか。
  • MixiへのログインにはHttpClientを使用するが、PostMethodやGetMethodの型解決エラーが発生してしまい、ログインができない。必要なライブラリが不足しているのかもしれない。
回答を見る
  • ベストアンサー

HttpClientについて

MixiにログインするサンプルプログラムがあったのでEclipse上動かそうと思い HttpClientのライブラリをダウンロードし実行しようとしたところ PostMethod、GetMethodについて型に解決できませんと出ました。 ダウンロードしたファイルの中にあった全てのjar(以下の6個)にパスを通したのですが まだ何かライブラリが足りないのでしょうか。 ・commons-codec-1.4.jar ・commons-logging-1.1.1.jar ・httpclient-4.1.2.jar ・httpclient-cache-4.1.2.jar ・httpcore-4.1.2.jar ・hhtpmime-4.1.2.jar import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpException; import org.apache.http.client.HttpClient; import org.apache.http.client.params.CookiePolicy; import org.apache.http.impl.client.DefaultHttpClient; public class MixiLogin2 { public static void main(String[] args) { HttpClient client = new DefaultHttpClient(); String mixiLogin = "http://mixi.jp/login.pl"; String mixiTopPage = "http://mixi.jp/home.pl"; String encode = "EUC-JP"; String inputUserName = "email"; String inputPassword = "password"; String inputNextUrl = "next_url"; String userName = "xxxxx@xxxxx.com"; String password = "xxxx123456789"; String nextUrl = "/home.pl"; PostMethod postMethod = new PostMethod(mixiLogin); postMethod.addParameter(inputUserName, userName); postMethod.addParameter(inputPassword, password); postMethod.addParameter(inputNextUrl, nextUrl); postMethod.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); try { int statusCode = client.executeMethod(postMethod); System.out.println(statusCode); postMethod.releaseConnection(); if (statusCode == 200) { GetMethod getMethod = new GetMethod(mixiTopPage); statusCode = client.executeMethod(getMethod); if (statusCode == 200) { BufferedReader br = new BufferedReader( new InputStreamReader(getMethod .getResponseBodyAsStream(), encode)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } } getMethod.releaseConnection(); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }

  • Java
  • 回答数1
  • ありがとう数1

質問者が選んだベストアンサー

  • ベストアンサー
回答No.1

GetMethodもPostMethodもimportされてないからでは。

unko347
質問者

お礼

インポートしようとしたところEclipse上でも GetMethodとPostMethodだけインポートの候補が表示されませんでした。 commons-httpclient-3.1.jarを導入したところインポートできるようになり 解決できました。

関連するQ&A

  • Xercesを使ったjavaでのXML解析

    DOMを使ってXML文書を解析するJavaのソースコードで、DOMパーサは、クラス org.apache.xerces.parsers.DOMParserで参照している下記のプログラムで、 [Fatal Error] :17:109: The entity name must immediately follow the '&' in the entity reference. org.xml.sax.SAXParseException; lineNumber: 17; columnNumber: 109; The entity name must immediately follow the '&' in the entity reference. のエラーが出てしまって、解決策が分かりかねています。Javaのネットワークプログラミングに詳しい方、御教示願えればと思います。 package nikkei; import java.io.ByteArrayInputStream; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class TwitterSearch { public static void main(String[] args) throws Exception { TwitterSearch search = new TwitterSearch(); search.search("日経ソフトウエア"); } public void search(String keyword) throws Exception { SearchAPIClient client = new SearchAPIClient(); String xml = client.execute(keyword); parse(xml); } private void parse(String xml) throws Exception { DOMParser parser = new DOMParser(); try { parser.parse(new InputSource(new ByteArrayInputStream(xml.getBytes()))); Document doc = parser.getDocument(); NodeList entries = doc.getElementsByTagName("entry"); for (int i = 0; i < entries.getLength(); i++) { String name = null; String tweet = null; Element entry = (Element) entries.item(i); NodeList titleList = entry.getElementsByTagName("title"); if (titleList.getLength() == 1) { tweet = titleList.item(0).getTextContent(); } NodeList authorList = entry.getElementsByTagName("author"); if (authorList.getLength() == 1) { Element author = (Element) authorList.item(0); NodeList nameList = author.getElementsByTagName("name"); if (nameList.getLength() == 1) { name = nameList.item(0).getTextContent(); } } System.out.println(name + "さんのツイート"); System.out.println("\t" + tweet); } } catch (Exception e) { e.printStackTrace(); } } } package nikkei; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class SearchAPIClient { public String execute(String keyword) throws Exception { String url = "https://twitter.com/search?q=" + keyword; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } else { return null; } } } よろしくお願いいたします。

    • ベストアンサー
    • Java
  • Servletでcsvファイル読込

    Servletからcsvファイルを読込む処理を作成しています。 しかし、FileNotFoundExceptionが発生してファイルを読込めません。 下記のように記述した場合、csvファイルはどこに置けばよいのでしょうか? いろいろファイルの置き場所を変えてはやってみましたがダメでした。 package action; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class MemberEntryAction extends Action{ public ActionForward execute(ActionMapping mapping,ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { // 入力ストリームを作成。 FileReader fr = new FileReader("a.csv"); BufferedReader br = new BufferedReader(fr); // 読込みループ。 String line; // 読み込まれた1行。 while( (line = br.readLine()) != null ) { System.out.println(line); } // 入力・出力ストリームを閉じる。 br.close(); fr.close(); } catch ( FileNotFoundException e ) { System.out.println("FileNotFound!"); } return mapping.findForward("memberMenu"); } }

  • CSV読み込み 文字化け

    失礼いたします。 以前のログを見てエンコードを設定してみたのですが、出力が文字化けします。ローカルファイルを読み込んでコンソール出力しているだけなのですが・・・。 分かる方、よろしくお願いします。 -------------------ソースはここから import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; // import java.io.FileReader; FileReaderからInputStreamReaderに変更済み import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class ReadCSV { public static void main(String[] args) { try { File csv = new File("C:\\AP.csv"); // BufferedReader br = new BufferedReader(new FileReader(csv)); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(csv),"EUC_JP")); // BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(csv),"MS932")); while (br.ready()) { String line = br.readLine(); StringTokenizer st = new StringTokenizer(line, ","); while (st.hasMoreTokens()) { System.out.print(st.nextToken() + "\t"); } System.out.println(); } br.close(); } catch (FileNotFoundException e) { キャッチ処理 }

    • ベストアンサー
    • Java
  • 入出力について

    下記のソースコードで、2点不明な点がありますので ご教授お願い致します。 import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class ab3{ public static void main(String args[]){ BufferedReader myReader = new BufferedReader( new InputStreamReader(System.in)); try{ System.out.println("名前を入力してください"); String myString = myReader.readLine(); System.out.println(myString + "さん、こんにちわ!"); }catch(IOException e) { } } } 1. BufferedReader myReader = new BufferedReader( new InputStreamReader(System.in)); ここのソースコードについてですが、 new BufferedReader(new InputStreamReader ^^^ ^^^ (System.in)); 「new」が二つもついていますが、何故二つも つける必要があるのでしょうか。 一つであっても問題はないと思われ、 2番目の「new」を取り除くと、エラーが表示されて しまいます。 また、上記ソースコードを BufferedReader myReader ; myReader = InputStreamReader(System.in)); と分割して書こうとしてもエラーが表示されてしまいます。 2. String myString = myReader.readLine(); ここの部分ですが、これはString型のインスタンス(コンストラクタ?)を 作っていると思われますが、この部分を String myString ; myString = myReader.readLine(); または、 String myString = new myReader.readLine(); としてたら、エラーが表示されてしまいます。 JAVAを初めて間もなく、質問の内容がわかりづらいと 思われます。入出力について理解するのに苦労して おりますが、何卒ご教授の程お願い致します。

    • ベストアンサー
    • Java
  • 答えを教えてください

    javaの課題でわからないことがあるので質問します。 2つ目のファイルに書かれているSgStdInTestを、 1つ目のファイルのどこかに入れてコンパイルして 動かせるようにしたいのですが、どうすればいいですか? よろしくおねがいします。 ______1つ目(ファイル名StdInTest.java)_ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class StdInTest { public static void main(String args[]){ try{ System.out.print("Input : "); BufferedReader r = new BufferedReader( new InputStreamReader(System.in)); String str = r.readLine(); System.out.println("Your Input : " + str); }catch(IOException e) { e.printStackTrace(); } } } ____2つ目(ファイル名SgStdInTest.java)______ class SgStdInTest{ private String input; public void setInput(String input){ this.input = input ; } public String getInput(){ return input; } }

  • HTTPでPOSTしてgooメールにログイン

    Javaを使用して、HTTPでgooメールにログインしたいのですが、うまくいきません。 サンプルを探して試しているのですが、レスポンスに「302」が返却されます。 HTTPヘッダの情報が足りないのか、POSTするデータが足りないのか、 はたまた、その他なにかしらが足りないのか、ご存知の方がおりましたら、教えて頂けないでしょうか? 以下apacheのhttpclientを使ったレスポンスに「302」が返却されるプログラムです。 public class http_test { public static void main(String[] args) { try { String url = "https://login.mail.goo.ne.jp/id/authn/Login"; String id = "gooID"; // gooID ※質問用にダミー値を設定 String pass = "password"; // パスワード ※質問用にダミー値を設定 String params = "uname="+ id +"&pass=" + pass + "&Site=mail.goo.ne.jp&Success=http://mail.goo.ne.jp"; HttpPost httpPost = new HttpPost( url ); DefaultHttpClient httpClient = new DefaultHttpClient(); StringEntity paramEntity = new StringEntity( params ); paramEntity.setChunked( false ); paramEntity.setContentType( "application/x-www-form-urlencoded" ); httpPost.setEntity( paramEntity ); HttpResponse response = httpClient.execute( httpPost ); int status = response.getStatusLine().getStatusCode(); if ( status != HttpStatus.SC_OK ) { // ここで「302」が返却される System.out.println(status); throw new Exception( "" ); } }catch(Exception e) { e.printStackTrace(); } } }

  • ブログサイトへの認証の仕方。

    SEESAAブログサイトにログインするプログラムを作成しているのですが。 ログインがうまくできません、以下のプログラムで、行うと、「認証に失敗しました」と記されたhtmlページが変数sbに戻ってきます。 「マイ・ブログ」と記されたhtmlページが変数sbに戻ってくるようにしたいです。 ご教授お願いいたします。 ----------------------------------------------------- import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import javax.net.ssl.HttpsURLConnection; import java.net.URL; public class SeesaaLogin { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); String crlf = null; try { URL url = new URL("https://ssl.seesaa.jp/auth"); HttpsURLConnection conH = (HttpsURLConnection)url.openConnection(); conH.setInstanceFollowRedirects(true); conH.setDoOutput(true); conH.connect(); OutputStream out = conH.getOutputStream(); PrintStream ps = new PrintStream(out); ps.print("email=xxx@xxxx.xx&password=xxxxxx&remember_me=t"); ps.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(conH.getInputStream(), "SJIS")); while (true) { String line = reader.readLine(); if ( line == null ){ break; } sb.append(line + crlf); } } catch(Exception e) { } System.out.println(sb); } } -----------------------------------------------------

  • Javaのカウント方法について

    お伺い致します。 CSVで取り込んだデータの抽出をしたいのですが、方法が見出せません。どの点を直せば宜しいのでしょうか。 具体的には取り込んだ郵便番号をカウントして(例:京都市,34)CSVファイルに出力するように出したいのですがカウントがうまくできません。(以下、コメントアウトしたものがありますが、今までのソースを記載します) 宜しく御願いします。 import java.io.FileReader; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.*; public class test01 { static String fname ="26KYOUTO.CSV"; public static void main(String[] args){ if(args.length>0) fname = args[0]; try { BufferedReader reader = new BufferedReader(new FileReader(fname)); BufferedWriter pw = new BufferedWriter(new PrintWriter("orig.txt")); String line = reader.readLine(); System.out.println(line); pw.println(""); int n = 0; int count = 0; _/* while(true) { String line = reader.readLine(); if(line.equals("26101")) break; count++; } */ reader.close(); System.out.println("京都府北区=" +count ); } catch(FileNotFoundException e) { System.out.println("ファイルがありません。"); } catch(IOException e) { System.out.println("入出力エラーです。"); } } }

    • ベストアンサー
    • Java
  • Java での グローバルIP取得

    Java を利用してグローバルIPの取得方法を探しています。 以下のサイトを参考にいたしました。 http://stackoverflow.com/questions/2939218/getting-the-external-ip-address-in-java 文中中ほどの以下のソースを試したのですが「checkip.amazonaws.com」と通信を行うせいか、ワンテンポページ表示に時間がかかります。 JavaでのグローバルIP取得するには他に良い方法はあるのでしょうか? それとも、whatismyipのようなサイトと通信を行わないとできないのでしょうか? よろしくお願い致します。 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; public class IpChecker { public static String getIp() throws Exception { URL whatismyip = new URL("http://checkip.amazonaws.com"); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader( whatismyip.openStream())); String ip = in.readLine(); return ip; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }

  • javaについて

    こういうプログラムを組んだんですが、うまく実行できません。 どんな改善をしたらよいでしょうか? import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class Sample { public static void main(String[] args) { String htmlSrc = getHTMLSrc("http://search.yahoo.co.jp/search?p=java", "UTF-8"); htmlSrc = htmlSrc.replaceAll("<.+?>| ", ""); htmlSrc = htmlSrc.replaceAll(".*件-", ""); htmlSrc = htmlSrc.replaceAll("秒.*", "秒"); System.out.println(htmlSrc); } private static String getHTMLSrc(String strURL, String charSet) { StringBuffer sb = new StringBuffer(); HttpURLConnection conn = null; BufferedReader br = null; try { URL url = new URL(strURL); conn = (HttpURLConnection)url.openConnection(); InputStreamReader isr = new InputStreamReader(conn.getInputStream(), charSet); br = new BufferedReader(isr); String tmp = ""; while ((tmp = br.readLine()) != null) { sb.append(tmp); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } if (conn != null) { conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } } 以下のエラーが表示されるんですが、どうしたらよいでしょうか?? 環境が悪いのでしょうか?? java.net.ConnectException: Operation timed out

    • ベストアンサー
    • Java

専門家に質問してみよう